package com.phx.serialjni;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Instrumentation;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.hardware.input.InputManager;
import android.media.AudioManager;
import android.media.AudioPlaybackConfiguration;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.AMapLocationQualityReport;
import com.phx.uart.MyFunc;
import com.phx.uart.SerialHelper;
import com.phx.uart.uartJni;
import com.phx.uart.uartJnit;
import com.phx.widget.ComBean;
import com.phx.widget.nSeekBar;
import com.utils.CRC16;
import com.utils.ThreadLocalDateUtil;
import com.utils.TransformUtils;
import com.utils.callMenu;
import com.utils.mapUtils;

import org.jetbrains.annotations.NotNull;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.math.RoundingMode;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class startActivity extends Activity {

    private  int onlyone = 0;
    RotateAnimation rotate;
    private  int allappsonlyone = 0;
    private  int exitapponlyone = 0;
    private  int havajmp = 0;
    private  int pauseonlyone = 0;
    private  int lastsonlyone = 0;
    private  int nextsonlyonce = 0;
    private  int lonlyone = 100;
    DispTimeThread DispTimeQueue;
    private  String  addresscode = "";
    private double lastseconds = 0.0;
   private boolean haveFinished = true;
    private boolean retfromabove = false;
    private LockScreenReceiver mReceiver;
    private ImageView iv_needle_time;   //码表针控件
    private ImageView iv_left_dot;
    private ImageView iv_right_dot;
    private ImageView iv_clock;
    private ImageView iv_needle_hour;
    private ImageView iv_needle_minute;
    private ImageView iv_needle_second;   //码表针控件
    private ImageView iv_center;   //码表针控件
    private TextView tv_date;
    int inithourv;
    int initminutev;
    int initsecondv;
    int hourv;
    int minutev;
    int secondv;
    int allsecond =0;
    ScheduledExecutorService newschpool = null;
    private float degree = 0;

    private boolean isAdjust;
    static  TextView testView;
    TextView testtView;
    TextView testfView;
    DispQueueThread DispQueue;//刷新显示线程
    myFrameLayout frame;
    myFrameLayout frameall;
    myFrameLayout frameseond  ;
    int maxC = 0;
    static String headerData = "5aa5";
    static SerialControl ComA;
    SerialControl ComB;//2个串口
    Handler  uiSwitch;
    public boolean isSel = false;
    public int currentPosition = -1;
    private String lcommand = "";
    private int jmpPostion = -1;
    private  boolean ismute = false;
    private MyConnection mConnection;
    private MusicService.MyBinder mBinder;
    private List<Music> mMusicList;
    private ListView mListView;
    private Context mContext;
    private int mPpositionOfPlaying;
    MeziView mezi;
   // upClicked = false;
   // private int isSel = 0;
   public static String SOCKET_ADDRESS = "com.clzk.mobilej.local";
    private  static String lastV = "";
    // static int fd;
    private  static final int SERVERPORT = 15001;
    private static  ServerThread serverThread = null;
    private static Map<String, Socket> clientMap = new HashMap<>();
    private static List<String> clientList = new ArrayList<>();
    private  static  Map<String, InputStream> clientdis = new HashMap<>();
    public  static  Map<String, OutputStream> clientdos = new ConcurrentHashMap<String, OutputStream>();
    private static WeakReference<startActivity> myown= null;

    public static boolean hasStarted = false;
    ExecutorService executor = new ThreadPoolExecutor
            (5 ,5 ,0, TimeUnit.MILLISECONDS,new LinkedBlockingQueue(10));
    ExecutorService trandisexecutor = new ThreadPoolExecutor
            (5 ,5 ,0, TimeUnit.MILLISECONDS,new LinkedBlockingQueue(20));
    ExecutorService acceptexecutor = new ThreadPoolExecutor
            (5 ,5 ,0, TimeUnit.MILLISECONDS,new LinkedBlockingQueue(10));
    static ExecutorService forwardexecutor = new ThreadPoolExecutor
            (5 ,5 ,0, TimeUnit.MILLISECONDS,new LinkedBlockingQueue(20));
   String cmdheader = "5AA50883";
  //  private static WeakReference<MainActivityf> myowna= null;
    ImageView pointValuea;
    ImageView pointValueb;
    boolean slidera = false;

    String feedheader = "5AA5";
    int   touchDownflag;
    static int lType = 1;
    private int isDown = 0;
    private int isUp = 0;
    private int isMove = 0;
    private int isCal = 0;
    private boolean nneed = false;
    private boolean isseek1feed = false;
    private boolean isseek2feed = false;
    private int firseekv = 0;
    private int isdengpressed = 0;
    private boolean isneidingon = false;
    private int lfirseekv = 102;
    private int lfirseekvt = 103;
    private int lfirseekvt1 = 103;
    private int lfirseekvt2 = 103;
    private boolean isfWeather = true;
    //private  String  addresscode ;

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
  //  private static MainActivityf mActivity = null;
    private static WeakReference<startActivity> myowna= null;
    public static final String SERVICECMD="com.android.music.musicservicecommand";

    public static final String CMDNAME="command";


    MeziView newm;
 //int currentPage = 0;   // 首页
 int currentPage = 29;   // 首页
 // int currentPage = 30;   // 首页
    byte[] read_buf = new byte[512];
    int fd;
    private SeekBar seekBar1;
    private SeekBar seekBar2;
    sPageJ pagestatus = new sPageJ();
    Rect currentRect = new Rect();
    private static final long TIMER_INTERVAL = 100;

    private static final long TIMER_INTERVAL1 = 1;
    TextView testwenView;
    TextView csView;
    TextView avertView;
    TextView swdView;
    ImageView csImgView;
    ImageView rndImgView;
    ImageView airqImgView;
    TextView locView;
    TextView airlocView;
    TextView ttView;
    TextView tdView;
    ImageView weatherImg ;
    TextView airqView;
    private CountTimer countTimerView;

   // TextView testtView;
    TextView testfenView;


    Handler handler = new Handler();

//             private  class SumHandler extends Handler {
//                 private WeakReference<MainActivityf> mActivity;
//
//                 public SumHandler(MainActivityf activity) {
//                     mActivity = new WeakReference<MainActivityf>(activity);
//
//                 }
//             }

    @SuppressLint("HandlerLeak")
    public Handler uHandler = new Handler(){
        //     private static Handler handler = new Handler();
//     @SuppressLint("HandlerLeak")
//   //   private  Handler uHandler = new SumHandler(this);
//    // private Handler uHandler = new Handler(new Handler.Callback(){
//
//     public Handler uHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            //   HandlerActivity activity = (HandlerActivity) mActivity.get();

            if(myowna!=null) {
                switch (msg.what) {
                    case 0:
                        break;


                    case 1:
                        String commandTxt = msg.getData().getString("alltext");
                        //if (commandTxt.length() > 10)

                        //
//                    if(sPageJpageno == 2)
//                    {
//                        if (commandTxt.length() > 10) {
//                            getvoltage(commandTxt);
//                        }
//                    }
//                    else
//
//                    {
//                        testtView.setText(commandTxt);
                        if (commandTxt.length() > 10) {

                            try {
                                refreshallui(commandTxt, lcommand);
                                lcommand = commandTxt;
                            } catch (Exception ex) {
                                renew();
                            }

                        }
                        //  }


                        break;
                    default:
                        break;
                }
            }
        }

    };


    private void initView() {
        //mListView = findViewById(R.id.listView);
//        mMusicList = MusicList.getMusicList(this);
//        if (mBinder == null){//mBinder is null that is what bindService is not finish
//            bindMusicService();
//        }else{
//           // showListView();
//        }
    }

    void   mania(ImageView imga,float vv)
    {
        try
        {
//
//             int x1= 273;
//             int x2=433;
//             int h1=333;
//             int h2=363;
//             int x1= 734;
//             int x2=857;
//             int h1=303;
//             int h2=323;

            //  if((vv > 10.4)&&(vv<14.6))
            if((vv > 9.9)&&(vv<14.6))
            {

//                 double xx1 =  273;
//                 double yy1 =  360;
//                 double r = 266;
//                 double halfjl = 175;
//                 int leftx = 271;
//                 int lefty= 360;
//                 int rightx = 430;
//                 int righty = 334;
//
//                 double alljd = Math.toDegrees(Math.atan(halfjl/r));
//                 double allhd = Math.toRadians(Math.atan(halfjl/r));
//               //  double bili = 0.1 * (vv-10)/10;
//                 double bili = (vv-10.4)/20.0;
//                 double nextjd = bili * alljd;
//                 double nexthd = bili * allhd;
//                 double rx = r * Math.sin(Math.toRadians(nextjd));
//                 double dx =  (int)(bili * halfjl);
//                 double gg = Math.cos(Math.toRadians(nextjd));
//
//                 double ry = r * (1 - gg);
//                 double dy =  ((int)ry);

//                 int  mx = (int)(xx1 + dx);
//                 int my = (int)(yy1 - dy);
//                 int md = (int) (0 - nextjd);

                int seq =(int) ((vv-9.9)*10/2);
                int mx = sPageJ.uarrowax[seq];
                int my = sPageJ.uarroway[seq];
                int mt = sPageJ.uarrowam[seq];
                int md = 0;
                // movePos(imga,mx,my,8,12, md);
                // movePos(imga,mx-4,my-6,8,12,md);
                movePost(imga,mx,my,8,12,md,mt);
            }
            else
            {
                movePos(imga,113,332-6,8,12,0);
            }

        }
        catch(Exception xx)
        {
            return;
        }

    }
    private void movePos(ImageView  Valueb,int x,int y,int w,int h,float d)

    {
        if (Valueb.getParent() == frame)
        {
            frame.removeView(Valueb);
        }
        // pointValueb.setRotation(d);
        //   Typeface typeface= Typeface.createFromAsset(getAssets(),"yj.ttf");

        FrameLayout.LayoutParams paramsb=new FrameLayout.LayoutParams( convertWn(w),convertHn(h));

        paramsb.leftMargin = convertWn(x)  ;
        paramsb.topMargin = convertHn(y)  ;

        // FrameLayout.LayoutParams paramsb=new FrameLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        Valueb.setLayoutParams(paramsb);
        // this.addContentView( pointValueb,params);
        frame.addView(Valueb,paramsb);
        // Valueb.setPivotX(convertWn(x+w/2));
        //  Valueb.setPivotY(convertHn(y+h/2));
        // Valueb.setRotation(d);
        // Valueb
    }

    private void movePost(ImageView  Valueb,int x,int y,int w,int h,float d,int t)

    {
        if (Valueb.getParent() == frame)
        {
            frame.removeView(Valueb);
        }
        // pointValueb.setRotation(d);
        //   Typeface typeface= Typeface.createFromAsset(getAssets(),"yj.ttf");

        FrameLayout.LayoutParams paramsb=new FrameLayout.LayoutParams( convertWn(w),convertHn(h));

        paramsb.leftMargin = convertWn(x)  ;
        paramsb.topMargin = convertHn(y)  ;
        Valueb.setImageDrawable(getDrawable(t));

        // FrameLayout.LayoutParams paramsb=new FrameLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        Valueb.setLayoutParams(paramsb);
        // this.addContentView( pointValueb,params);
        frame.addView(Valueb,paramsb);

    }
    void   manib(ImageView imga,float vv)
    {
        try
        {


            // double halgrot = Math.toDegrees(Math.atan(halfjl/r));


            int x1= 734;
            int x2=857;
            int h1=303;
            int h2=323;

            // if((vv > 10.4)&&(vv<14.6))
            if((vv > 9.9)&&(vv<14.6))
            {

//                double xx1 = 734;
//               double yy1 = 332;
//                double r = 259;
//                double halfjl = 130;
//                int leftx = 739;
//                int lefty= 332;
//                int rightx = 855;
//                int righty = 308;
//
//                double alld = Math.toDegrees(Math.atan(halfjl/r));
//                double bili = (vv-10)/10.0;
//                double nextd = bili * alld;
//              //  double dx = r * Math.sin(Math.toRadians(nextd));
//                double dx =  ((vv-10) * halfjl)/10;
//                double dy = r * (1-Math.cos(Math.toRadians(nextd)));
//
//                int  mx = (int)(xx1 + dx);
//                int my = (int)(yy1 - dy);
//                int md = (int) (0 - nextd);
//
//                // movePos(imga,mx,my,8,12, md);
//                  movePos(imga,mx,my,6,9,md);
                int seq =(int) ((vv-9.9)*10/2);
                // int seq =(int) ((vv-9.9)*10/2);
                int mx = sPageJ.uarrowbx[seq];
                int my = sPageJ.uarrowby[seq];
                int mt = sPageJ.uarrowbm[seq];
                int md = 0;
                // movePos(imga,mx,my,8,12, md);
                // movePos(imga,mx-4,my-6,8,12,md);
                movePost(imga,mx,my,6,9,md,mt);
                //   movePost(imga,785,323,6,9,md,mt);
            }
            else {
                movePos(imga,611,309-4,6,9,0);
            }
        }
        catch(Exception xx)
        {
            return;
        }

    }

    void  disv(String device,String stat)
    {
        if(sPageJ.voladdress[0].equals(device)){
            //  int fir = Integer.parseInt(stat.substring(2,3));
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
            float lastx = (float) 0.0;
            lastx = (float)(value/10.0);
            NumberFormat formatter = new DecimalFormat("00.0");

            String formmatedFloatValue = formatter.format(lastx);
            if((lastx > 9.9) && (lastx < 14.6)) {
                if(testView == null) {

                }
                else {

                    if(sPageJ.pageno == 30) {
                        mania(pointValuea, lastx);

                        testView.setText(formmatedFloatValue);
                    }

                }
            }
            else
            {
                // movePos();
                // movePos(pointValuea,307,355,8,12,0);
                // mania(pointValuea,(float)14.0);
            }
        }
        if(sPageJ.voladdress[1].equals(device)){
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
            // int value = BigInteger(fir,16);
            float lasty = (float) 0.0;
            lasty = (float)(value/10.0);
            NumberFormat formatter = new DecimalFormat("00.0");

            String formmatedFloatValue = formatter.format(lasty);
            if((lasty > 9.9) && (lasty < 14.6)) {
                if(testfView == null) {

                }
                else {
                    if(sPageJ.pageno == 30) {
                        manib(pointValueb, lasty);
                        testfView.setText(formmatedFloatValue);
                    }
                }
            }
            else {
                // movePos(pointValueb,761,325,6,9,0);
                // mania(pointValueb,(float)14.0);
            }
        }
    }

    private void bindMusicServicex() {
        Intent intent = new Intent();
        intent.setClass(this, MusicService.class);
        intent.putExtras(getIntent().getExtras());
        startService(intent);
        mConnection = new MyConnection();
        bindService(intent, mConnection, BIND_AUTO_CREATE);
       // Log.i(TAG, "mBinder:"+ mBinder);
    }
    private void bindMusicService() {
        Intent intent = new Intent();
        intent.setClass(this, MusicService.class);
        mConnection = new MyConnection();
        bindService(intent, mConnection, BIND_AUTO_CREATE);
        //Log.i(TAG, "mBinder:"+ mBinder);
    }

    private  void refreshallui(String comingdata,String lcomingdata)
    { Log.e("coming str:",""+comingdata);

//        if(!checkability(comingdata,lcomingdata)) {
//            return;
//        }
        //moni data

       // 0x5A	0xA5	0x19（25）	0x82	0x1A	0x10	0x00	0x78	0x00	0x78	0x00	0x50	0x00	0x16	0x00	0x18
        // 0x00	0x04	0x00	0x20	0x00	0x20	0x00	0x00	0x00	0x00  0xab  0xcd
       // 0x5A	0xA5	0x19（25）	0x82	0x1A	0x10	0x00	0x78	0x00	0x78	0x00	0x50	0x00	0x16	0x00	0x18	0x00	0x04	0x00	0x20	0x00	0x20	0x00	0x00	0x00	0x00	CRCHi	CRCLo
        //后续字节长度		反馈地址1A10		主电压		副电压		车速		车内实际温度		空调设定温度		空调风量		PM2.5		空气质量		预留1		预留2		CRC

      //  comingdata = "5aa50d8240010001000000000000bb1a";
        //comingdata = "5aa50d8230010001000100010001abcd";
      //  comingdata = "5aa51d820ee100010000000000000000000000000000000000000000000153cd";
          //comingdata = "5aa519821a100001000100810001000100010001002200010001abcd";
        //comingdata = "5aa50982600100060003abcd"
       // comingdata = "5aa50982600100060003abcd"; //kongtiao
        //5aa511822fe1000100000001000100000000392d
        // comingdata = "5aa50982e00100190005abcd"; //kongtiao
       // comingdata = "5aa509826001000600adabcd"; //kongtiao
      //  comingdata = "5aa5098210110070005f3bb8"; //副电压11.2
       //  comingdata = "5aa5098210100070005f3bb8"; //主电压11.2
        // comingdata =   "5aa509821010005d005d2a70";
      //  comingdata =   "5aa50982600100070015fd66";
        String message = "";

//        if (comingdata.length() >= 48) {
//            message = comingdata.substring(0, 48);
//            //  Log.e("coming str:",""+message);
//        }
//        else
//        {
//            message = comingdata;
//        }

        message = comingdata;
        // String message = comingdata;
        String firstFour ="";
        // message = "5aa515820ee1000000010000000000000000000100005d8e";
        // message = "5aa5118200d10000000100000000000000009cdf";
        // message = "5aa515820ee1000000000000000000320020000000015dob";
        //   message = "5aa515820ee1000000010000000000320020000100015dob";
        //音量是50 低音音量32  蓝牙有反馈
        // message ="5aa515820ee100000000000000000032002000010000cd";
        //  message ="5aa513820ee100010000001f0010001f001000029de3";
        //message = "5aa50782e00e00000a1d";
        //  message = "5aa515820ee1000000000038003e0038003e000000019208";
        // 音量是50 低音音量32  HDMI有反馈
        if((message.length())> 4)
        {                firstFour = message.substring(0, 4);
        }

        int positionInBoard = 0;


//                if (firstFour.equals(headerData)) {
//                    int msgcounts = Integer.parseInt(message.substring(4, 6), 16);
//                    int countsw = (msgcounts - 7) / 2 + 1;
//                 //  message = message.substring(0, countsw * 2 + 6);
//                }
//                else {
//                    return;
//                }

        int counts = 0;
        if (message.length() > 19) {

            int msgcounts = Integer.parseInt(message.substring(4, 6), 16);
            counts = (msgcounts - 7) / 2 + 1;

            String[] feedDevice = new String[counts];
            String[] feedStatus = new String[counts];

            if (counts == 1) {


                String feedDevicex = message.substring(8, 12);

                String deviceStaus = message.substring(12, 16);

                Message msg = new Message();
                //  if (isSend) {
                //   msg.what = 1;
                // .get(sPageJfeedDArray[jmpPostionx]);
                if (feedOK(feedDevicex)) {
                    String ntype = sPageJ.feedType.get(feedDevicex);
                    msg.what = Integer.parseInt(ntype);
                }
                // msg.obj = deviceStaus;
                Bundle bundle = new Bundle();
                bundle.putString("feedDevice", feedDevicex);
                bundle.putString("feedStatus", deviceStaus);
                msg.setData(bundle);
                if (feedOK(feedDevicex)) {
                    sPageJ.feedMap.put(feedDevicex, deviceStaus);
                }
                mHandler.sendMessage(msg);
            } else {
                for (int cc = 0; cc < counts; cc++) {
                    feedDevice[cc] = TransformUtils.getAddress(message.substring(8, 12), cc);
                    feedStatus[cc] = message.substring(12 + cc * 4, 16 + cc * 4);

                    Message msg = new Message();
                    //  if (isSend) {
                    if (feedOK(feedDevice[cc])) {
                        String ntype = sPageJ.feedType.get(feedDevice[cc]);
                        msg.what = Integer.parseInt(ntype);
                    }
                    //  msg.what = 1;
                    Bundle bundle = new Bundle();
                    bundle.putString("feedDevice", feedDevice[cc]);
                    bundle.putString("feedStatus", feedStatus[cc]);
                    msg.setData(bundle);
                    if (feedOK(feedDevice[cc])) {
                        sPageJ.feedMap.put(feedDevice[cc], feedStatus[cc]);
                    }
                    mHandler.sendMessage(msg);
                }
            }
        }
    }


    public void setInitcmd(int currentPage) {
        switch (currentPage) {

            case 0:
                sendStart("10020000");
                //  sendStart("");
                //   sendStart("FE100000");
                //   int tmp = readFeedback();
                break;
            case 1:
                sendStart("10010000");
                break;
            case  2:
                 sendStart("BC110200");
                break;


//            case  3:
//                 sendStart("BC110300");
//             //   psendStart("5AA50883BC440000045B00");
//                break;

            case  4:
                sendStart("BC050000");
                break;
            case  204:
                sendStart("BC050000");
                break;

            case 29:
                sendStart("BC000000");
                break;
            case  229:
                sendStart("BC000000");
                break;
//            case  5:
//                sendStart("BC050000");
//            case  6:
//                sendStart("BC110600");
//            case  7:
//                sendStart("BC110700");
//
//            case  8:
//                sendStart("BC110800");
//
//            case  9:
//                sendStart("BC110900");
//            case  10:
//                sendStart("BC110A00");
//            case  11:
//                sendStart("BC110B00");
//            case  12:
//                sendStart("BC110C00");
//
//            case  13:
//                sendStart("BC110D00");
//
//            case  14:
//                sendStart("BC110E00");
//            case  15:
//                sendStart("BC110F00");
//            case  16:
//                sendStart("BC111000");
//            case  17:
//                sendStart("BC111100");
//            case  18:
//                sendStart("BC111200");
//            case  19:
//                sendStart("BC111300");
//            case  20:
//                sendStart("BC111400");
//            case  21:
//                sendStart("BC111500");
//            case  22:
//                sendStart("BC111600");
//            case  23:
//                sendStart("BC111700");
//            case  24:
//                sendStart("BC111800");
//            case  25:
//                sendStart("BC111900");
//            case 26:
//                sendStart("BC111A00");
//            case  27:
//                sendStart("BC111B00");
//            case  28:
//                sendStart("BC111C00");
//            case  29:
//                sendStart("BC111D00");
//            case  30:
//                sendStart("BC111E00");
//            case  31:
//                sendStart("BC111F00");
//            case  32:
//                sendStart("BC112000");
//            case  33:
//                sendStart("BC112100");
//
//            case  34:
//                sendStart("BC112200");
//            case  35:
//                sendStart("BC112300");
//            case  36:
//                sendStart("BC112400");
                //0~36  BC110000 ~ BC112400

                //  uartJnit.re
//                new Thread(
//                        new Runnable() {
//                            @Override
//                            public void run() {
//                                try {
//                                    Thread.sleep(100);
//                                    sendStart("FE10000");
//                                }
//                                catch(Exception ex)
//                                {
//
//                                }
//                            }
//                        }
//
//                ).start();



            default:

                break;
        }
    }

    private  void reciteallui(String comingdata)
    {


        String message = "";

        // String[] tmpAlla = new String[]{"d001", "f002", "d002", "f003","f00d", "f006", "f004","1010","1011","71b0","72b0","73b0"};

        int countsall = sPageJ.tmpAlla.length;

        for(int i=0; i < countsall ; i++) {
            Message msg = new Message();
            String feedDevicex = sPageJ.tmpAlla[i];
            String ntype = sPageJ.feedType.get(feedDevicex);
            msg.what = Integer.parseInt(ntype);
            // msg.obj = deviceStaus;
            Bundle bundle = new Bundle();
            bundle.putString("feedDevice", feedDevicex);
            String deviceStaus = "";
            if (feedOK(feedDevicex)) {
                deviceStaus = sPageJ.feedMap.get(feedDevicex);
            }
            bundle.putString("feedStatus", deviceStaus);
            msg.setData(bundle);

            mHandler.sendMessage(msg);

        }


    }

    void refreshui(int keyy)
    {
        //remove old

        removeAll();


        pagestatus.setInit(keyy);

        currentPage = sPageJ.pageno;
        //pagestatus.allRect = pa
        //invoke event
        mezi = new MeziView(startActivity.this);
        //为我们的萌妹子添加触摸事件监听器
        // mezi.setOnTouchListener(new OnTouchListener() {
        //  @Override
        // public boolean onTouch(View view, MotionEvent event) {
        //设置妹子显示的位置

        mezi.bitmapX = 100;
        mezi.bitmapY = 100;
//        mezi.mleft = convertW(0);
//        mezi.mtop = convertH(0);
//        mezi.mwidth = convertW(10);
//        mezi.mheight = convertH(10);

        mezi.mleft = convertWn(0);
        mezi.mtop = convertHn(0);
        mezi.mwidth = convertWn(10);
        mezi.mheight = convertHn(10);
        // mezi.mRes = R.drawable.b2_off;
        mezi.type = 1;
        // mezi.setVisibility(View.INVISIBLE);
        mezi.setClickable(true);
        String allCmdx = cmdheader;
        String tmpTmp = "C1200009";
        // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
        StringBuffer allCmd = CRC16.crc16x(allCmdx);
        // mezi.setTag(allCmd.toString());
        mezi.setId(0);
        // frame.setTag(allCmd.toString());
        mezi.setOnTouchListener(new TouchListenerx());
        // expandViewTouchDelegate(mezi,0,0,0,0);
        // frame.setClickable(false);

        frame.setEnabled(false);
        frame.addView(mezi,-1);
        frame.setBackgroundResource(sPageJ.pageback);
        //   frame.setBackgroundResource(R.drawable.a6);
        // frame.addView(mezi,0);
        // frame.invalidate();

        addmezis();
        //
//        if(keyy == 0) {
//           // createSeek31();
//            //createSeekb();
//        }
//        if(keyy == 1) {
//         //   createSeek31();
//           // createV();
//        }
//
//        if(keyy == 3) {
//           // createSeek31x();
//           // createSeek32();
//            // createbtns();
//        }
        //  getaddMezi(5);
        // frame.addView(mezi,maxC);

        // testFeed(5);
        // frame.addView(mezi,1);
        //// add feed status

        /// add original icon for feed type  19 ?
        /// rect mingan for diandong type 16 ?


        //frame.addV
        // pagestatus.setInit(currentPage);
        //addnews setid
        //findallrects
        //getcurrent
        // currentRect =

        if(keyy == 1)
        {
         //   createRQ();
        }
        if(keyy == 201)
        {
            //createRQ();
        }
        if(keyy == 4)
        {
            createWF();
        }
        if(keyy == 204)
        {
            createWF();
        }

        if(keyy == 52) {
            createSeek31();
            createSeek32();
            // createbtns();
        }

        if(keyy == 252) {
            createSeek31();
            createSeek32();
            // createbtns();
        }
//
        if(keyy == 29) {
            havajmp = 0;
         createWait();

        }
        if(keyy == 229) {
            createWait();
        }
       //  setInitcmd(keyy);
    }


    public  void createV()
    {
       // TextView  testfView,testView;

        testfView = new TextView(this);


        testfView.setText("0.0");

        pointValuea = new ImageView(this);

        pointValuea.setImageDrawable(getDrawable(R.drawable.ee1));


        pointValueb = new ImageView(this);


        pointValueb.setImageDrawable(getDrawable(R.drawable.ee2));



        String tmpStat = sPageJ.feedMap.get(sPageJ.allDArray[9]);
        if(!tmpStat.equals("0000"))
        {
            disv(sPageJ.allDArray[9],tmpStat);

        }
        else
        {
            // mania(pointValuea,(float)10.5);

            if(sPageJ.pageno == 30)   manib(pointValueb,(float)0.0);
        }

        Typeface typeface= Typeface.createFromAsset(getAssets(),"yj.ttf");
        testfView.setTypeface(typeface);//第一句话“离离原上草，一岁一枯荣”引入lanti.ttf字体库

        testfView.setTextColor(getResources().getColor(R.color.colorPrimary));
        // testfView.setTextSize(158);
        // testfView.setTextSize(79);
        // testfView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 108);
        testfView.setTextSize(128);
        testfView.setGravity(Gravity.CENTER);
        //    testfView.setGravity(Gravity.RIGHT);

        testfView.setText("0.0");
        int mWidth = testfView.getMeasuredWidth();
        int mHeight = testfView.getMeasuredHeight();
//        FrameLayout.LayoutParams paramsf=new FrameLayout.LayoutParams(convertWn(149),convertHn(86));
//      //  paramsf.leftMargin = convertWn(687) + mWidth/2 ;
//     //   paramsf.topMargin = convertHn(186) +  mHeight / 2;
//        paramsf.leftMargin = convertWn(671)   ;
//        paramsf.topMargin = convertHn(175)   ;

//         FrameLayout.LayoutParams paramsf=new FrameLayout.LayoutParams(convertWn(162),convertHn(88));
//
//        paramsf.leftMargin = convertWn(624)   ;
//        paramsf.topMargin = convertHn(173)   ;
        FrameLayout.LayoutParams paramsf=new FrameLayout.LayoutParams(convertWn(174),convertHn(118));

        paramsf.leftMargin = convertWn(655)   ;
        paramsf.topMargin = convertHn(150)   ;

        testfView.setLayoutParams(paramsf);
        frame.addView(testfView,paramsf);
        //    frame.addView(testfView);
        testView = new TextView(this);
        // testView.setMargins(convertWn(566), convertHn(268), convertWn(936), convertHn(303));
        //  testView.setPadding(convertWn(187), convertHn(176), convertWn(422), convertHn(278));
        // testView.setPadding(187, 156, 422, 278);
        testView.setText("0.0");
        //  testView.setText("1" + "2.5");
        testView.setGravity(Gravity.CENTER);
        String ftmpStat = sPageJ.feedMap.get(sPageJ.allDArray[8]);
        if(!ftmpStat.equals("0000"))
        {
            disv(sPageJ.allDArray[8],ftmpStat);
        }
        else
        {
            if(sPageJ.pageno == 30) mania(pointValuea,(float)0.0);

            // manib(pointValueb,(float)10.5);
        }

        //   Typeface typeface= Typeface.createFromAsset(getAssets(),"yj.ttf");
        testView.setTypeface(typeface);//第一句话“离离原上草，一岁一枯荣”引入lanti.ttf字体库

        testView.setTextColor(getResources().getColor(R.color.colorPrimary));
        // testView.setTextSize(232);
        testView.setTextSize(180);


        //   LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        FrameLayout.LayoutParams params=new FrameLayout.LayoutParams( convertWn(302),convertHn(198));

//        params.leftMargin = convertWn(187) + tWidth/2 ;
//        params.topMargin = convertHn(166) +  tHeight / 2;
        params.leftMargin = convertWn(130)  ;
        params.topMargin = convertHn(100)  ;
        testView.setLayoutParams(params);
        // this.addContentView(testView,params);
        // testView.setText("12".concat(".5"));
        frame.addView(testView,params);
        //   MainActivityw.AsyncTaskRunner runner = new MainActivityw.AsyncTaskRunner();
        //String sleepTime = "10:0000000123456";
        //  runner.execute();

    }

    public  void createSeek31()
    {
        seekBar1 = new nSeekBar(this);
        //  seekBar1 = new VerticalSeekBar(this);

        Drawable draw = getResources().getDrawable(R.drawable.g2);

        seekBar1.setProgressDrawable(getDrawable(R.drawable.thumb_image31));

        //  seekBar1.setThumb(getDrawable(R.drawable.thumb_image31));
        seekBar1.setThumb(getDrawable(R.drawable.g3));

        seekBar1.setMinimumHeight(convertHn(0));

        //FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(convertWn(247), convertHn(25));
        FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(218, 26);

        headParams.leftMargin = convertWn(308);
        //  headParams.topMargin = convertHn(136);
        headParams.topMargin = convertHn(234);

        seekBar1.setLayoutParams(headParams);

        //  seekBar1.setPadding(convertWn(0), convertHn(7), convertWn(0), convertHn(7));

        seekBar1.setPadding(convertWn(0), 0, 0, 0);
        seekBar1.setSplitTrack(false);
        seekBar1.setThumbOffset(convertWn(0));
        //      frame.addView(testView);
        frame.addView(seekBar1);
        // seekBar.setPadding(500,100, 50,700);
        seekBar1.bringToFront();
        seekBar1.setMax (100);
        seekBar1.setKeyProgressIncrement(1);

        seekBar1.setTag(1);
        //  seekBar1.setOnSeekBarChangeListener(this);

        seekBar1.setOnSeekBarChangeListener(onseek1);
//************
//        for (int hh=1;hh<2;hh++) {
//
//            String tmpStat = sPageJ.feedMap.get(sPageJ.allDArray[hh+10]);
//            if (!tmpStat.equals("0000")) {
//                dish(sPageJ.allDArray[hh+10], tmpStat);
//            }
//       }
        String tmpStat = sPageJ.feedMap.get(sPageJ.allDArray[22]);
        // if (!tmpStat.equals("0000")) {
         disvol(sPageJ.allDArray[22], tmpStat);
        // }

    }
    public  void createSeek32()
    {
        // seekBar2 = new VerticalSeekBar_Reverse(this);
        seekBar2 = new nSeekBar(this);
        // seekBar2 = new SeekBar(this);

        // seekBar2.setTag(2);
        Drawable draw = getResources().getDrawable(R.drawable.g8);

        seekBar2.setProgressDrawable(getDrawable(R.drawable.thumb_image32));

        //   seekBar2.setThumb(getDrawable(R.drawable.d11));
        seekBar2.setThumb(getDrawable(R.drawable.g9));

        seekBar2.setMinimumHeight(convertHn(0));

        FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(convertWn(218), convertHn(26));

        headParams.leftMargin = convertWn(308);
        headParams.topMargin = convertHn(356);
        // headParams.topMargin = convertHn(108);

        seekBar2.setLayoutParams(headParams);

        seekBar2.setPadding(0, 0, 0, 0);

        seekBar2.setSplitTrack(false);
        seekBar2.setThumbOffset(convertWn(0));
        //      frame.addView(testView);
        frame.addView(seekBar2);
        // seekBar.setPadding(500,100, 50,700);
        seekBar2.bringToFront();
        // seekBar2.setOnSeekBarChangeListener(this);

        //seekBar.setMin(1);

        seekBar2.setMax (100);
        // seekBar2.setKeyProgressIncrement(10);
        seekBar2.setKeyProgressIncrement(1);
        seekBar2.setTag(2);

//        for (int hh=2;hh<3;hh++) {
//            String tmpStat = sPageJ.feedMap.get(sPageJ.allDArray[hh+10]);
//            if (!tmpStat.equals("0000")) {
//                dish(sPageJ.allDArray[hh+10], tmpStat);
//            }
//        }

        String tmpStat = sPageJ.feedMap.get(sPageJ.allDArray[23]);

         disvol(sPageJ.allDArray[23], tmpStat);


//        SeekBar.OnSeekBarChangeListener onseek = new SeekBar.OnSeekBarChangeListener() {
//            @Override
//            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//
//                int type = 0;
//                int tmp = (int) seekBar.getTag();
//                 int firpara = progress  ;
//
//               // int firpara = progress / 10 ;
////        if (feedOK(feedDevice[cc])) {
////            sPageJ.feedMap.put(feedDevice[cc], feedStatus[cc]);
////        }
//               // String myvalue = revertValue(firpara * 10);
//                if (feedOK(sPageJ.allDArray[10+tmp])) {
//                   // sPageJ.feedMap.put(sPageJ.allDArray[10+tmp], revertValue(firpara * 10));
//                    sPageJ.feedMap.put(sPageJ.allDArray[10+tmp], revertValue(firpara));
//                }
//
//
//                //  testView.setText("当前数值："+ firpara);
//                if((firpara < 100)&&(firpara!=lfirseekvt)) {
//                    //   String cmdx = sPageJ.sliderCmd[tmp][firpara];
//                  //  String cmdx = sPageJ.sliderCmd[tmp][firpara];
//
//                    String cmdx = getNextCmd(tmp,firpara);
//                    // if (progress % 10 == 0) {
//                    //          testtView.setText("当前数值：" + cmdx);
//
//                    try {
//                        pslidersend(cmdx);
//
//                           // slidersend(tmp, firpara);
//                            lfirseekvt = firpara;
//
//                    }
//                    catch(Exception ex)
//                    {
//                        return;
//                    }
//                    //          }
//                }
//
//            }
//
//            @Override
//            public void onStartTrackingTouch(SeekBar seekBar) {
//
//            }
//
//            @Override
//            public void onStopTrackingTouch(SeekBar seekBar) {
//
//            }
//        };

        seekBar2.setOnSeekBarChangeListener(onseek2);

    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
  //      if (keyCode == KeyEvent.KEYCODE_BACK
   //             && event.getAction() == KeyEvent.ACTION_DOWN) {
//            for (Activity activity : ParameterSetActivity.activityList) {
//                activity.finish();
//            }
        //if (keyCode == KeyEvent.KEYCODE_BACK)
           // !retfromabove
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                if ((sPageJ.pageno == 0)||(sPageJ.pageno == 200)) {
            this.finish();
            System.exit(0);
            return false;
        }
//                else
//           if ((sPageJ.pageno == 29)||(sPageJ.pageno == 299)) {
//
//               bring2Front();
//           }

//                else
//            if ((sPageJ.pageno == 0)||(sPageJ.pageno == 200)) {
//                    int xxx = sPageJ.pageno - 1;
//                    //  String cmdOnex = "" + xxx;
//                    Message msg = new Message();
////                        if(currentPosition == 1)
////                            touchDownflag=300;
////                        else
//                    //   touchDownflag=3;
//                    // uartJni.read(fd, read_buf, read_buf.length);
//                    //  handler.postDelayed(runnable,100);
//                    String cmdOnex = "29";
//                    String[] jmpsrc = {"0", "1", "2", "3", "4", "5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","29","30",
//                            "31","32","33","21","22","23","41","42","43","51","52","53","71","72","73","81","82","83","181","182",
//                            "200", "201", "202", "203", "204", "205","206","207","208","209","210","211","212","213","214","215","216","217","218","219","229","230",
//                            "231","232","233","221","222","223","241","242","243","251","252","253","271","272","273","281","282","283","381","382"
//                    };
//
//                    msg.what = 3;
//                    //msg.obj = cmdOnex;
//                    msg.obj = cmdOnex;
//                    Bundle bundle = new Bundle();
//                    bundle.putString("jmppageno", cmdOnex);
//
//                    msg.setData(bundle);
//
//                    mHandler.sendMessage(msg);
//                    return true;
//                }

        else
        {
            int xxx = sPageJ.pageno - 1;
          //  String cmdOnex = "" + xxx;
            Message msg = new Message();
//                        if(currentPosition == 1)
//                            touchDownflag=300;
//                        else
            //   touchDownflag=3;
            // uartJni.read(fd, read_buf, read_buf.length);
            //  handler.postDelayed(runnable,100);
            String cmdOnex = "0";
            String[] jmpsrc = { "201", "202", "203", "204", "205","206","207","208","209","210","211","212","213","214","215","216","217","218","219","229","230",
                    "231","232","233","221","222","223","241","242","243","251","252","253","271","272","273","281","282","283","381","382"
            };


                if (TransformUtils.IsInArray(jmpsrc, sPageJ.pageno  + "")) {
                    // refreshui(jmpPostion);
                    refreshui(jmpPostion);
                    cmdOnex = "200";
                }


            msg.what = 3;
            //msg.obj = cmdOnex;
            msg.obj = cmdOnex;
            Bundle bundle = new Bundle();
            bundle.putString("jmppageno", cmdOnex);

            msg.setData(bundle);

            mHandler.sendMessage(msg);
            return true;
        }
        }
       return super.onKeyDown(keyCode, event);
       // return false;
    }

    private  boolean  checkability(String comingdata,String lcomingdata)
    {
        boolean result1 = false;
        boolean result2 = true;
        boolean result3 = true;
        boolean result = false;

        try {
            if(lcomingdata.equals(comingdata))
            {
                return false ;
            }
            int alllength = comingdata.length() - 3;
            String firstFour = "";
            if ((comingdata.length()) > 4) {
                firstFour = comingdata.substring(0, 4);
                if (firstFour.equals(headerData)) {
                    int msgcounts = Integer.parseInt(comingdata.substring(4, 6), 16);
                    if (alllength == (msgcounts * 2 + 3)) {
                        result1 = true;
                    }
                    //   int countsw = (msgcounts - 7) / 2 + 1;
                    //  message = message.substring(0, countsw * 2 + 6);
                }

                String feedDevicex = comingdata.substring(8, 12);
                if(!feedOK(feedDevicex))
                {
                    result2 = false;
                }

                int crccounts = 0;
                int crclength = comingdata.length();
                int allcounts = Integer.parseInt(comingdata.substring(4, 6), 16);
                // crccounts = (allcounts - 7) / 2 + 1;
                boolean crcbool1 = crclength >= allcounts + 3?true:false;

                boolean crcbool2 = comingdata.substring(2, 4).equals("a5");
                boolean crcbool3 = comingdata.substring(6, 8).equals("82");

                String hecrc = comingdata.substring(6, 2*(allcounts-2) + 6);
                // byte[] tempByte =  TransformUtils.hexStringToBytes(hecrc);
                // byte[] tempByte =  hexString2Intger(hecrc);
                //nCRC16(tempByte,allcounts-2);
//                 char uchCRCHi = ;   //CRC高字节
//                 char uchCRCLo;   //CRC低字节
//                 tempByte[9]=(byte)(uchCRCHi);
//                 tempByte[10]=(byte)(uchCRCLo);
                // StringBuffer mcrcstr = CRC16.crc16x(hecrc);
                byte[] tmpxx =  getSendBuf(hecrc) ;
                String lastvalue = getBufHexStr(tmpxx);
                // String mcrcstr = CRC16.myCRC16(hecrc);
                // final String cmdw = allCmd.substring(0, 22);
                String rcrcstr =  comingdata.substring(crclength-4, crclength);

                int clen = lastvalue.length();
                String cccstr = lastvalue.substring(clen-4, clen).toLowerCase();
                boolean crcbool4 = rcrcstr.equals(cccstr)? true: false;
                // boolean crcbool4 = rcrcstr.equals(mcrcstr)? true: false;

//                 if((RxCounter>=RxBuffer[2]+3)&&(RxBuffer[1]==0xA5)&&(RxBuffer[3]==0x82)){
//                     RxCounter=0;
//                     CRC16(&RxBuffer[3],5);
//                     if((RxBuffer[8] == uchCRCHi) && (RxBuffer[9] == uchCRCLo))
                result3 = crcbool1 && crcbool2 && crcbool3 && crcbool4;
            }



            result = result1 && result2 && result3;
        }
        catch(Exception ex)
        {
            //result = false;
            renew();
        }

        return result;
    }

    public  byte[] hexString2Intger(String str) {
        byte[] byteTarget = new byte[11];
        for (int i = 0; i < str.length() / 2; ++i)
            byteTarget[i] = (byte)(Integer.parseInt(str.substring(i * 2, i * 2 +2), 16) & 0xff);
        return byteTarget;
    }
    public static String getBufHexStr(byte[] raw) {
        String HEXES = "0123456789ABCDEF";
        if (raw == null) {
            return null;
        }
        final StringBuilder hex = new StringBuilder(2 * raw.length);
        for (final byte b : raw) {
            hex.append(HEXES.charAt((b & 0xF0) >> 4)).append(
                    HEXES.charAt((b & 0x0F)));
        }
        return hex.toString();
    }

    public static byte[] getSendBuf(String toSend) {
        byte[] bb = HexString2Buf(toSend);
        int ri = alex_crc16(bb, bb.length - 2);
        bb[bb.length - 2] = (byte) (0xff & ri);
        bb[bb.length - 1] = (byte) ((0xff00 & ri) >> 8);
        return bb;
    }

    public static byte[] HexString2Buf(String src) {
        int len = src.length();
        byte[] ret = new byte[len / 2 + 2];
        byte[] tmp = src.getBytes();
        for (int i = 0; i < len; i += 2) {
            ret[i / 2] = uniteBytes(tmp[i], tmp[i + 1]);
        }
        return ret;
    }

    private static byte uniteBytes(byte src0, byte src1) {
        byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
                .byteValue();
        _b0 = (byte) (_b0 << 4);
        byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
                .byteValue();
        byte ret = (byte) (_b0 ^ _b1);
        return ret;
    }
    static int alex_crc16(byte[] buf, int len) {
        int i, j;
        int c, crc = 0xFFFF;
        for (i = 0; i < len; i++) {
            c = buf[i] & 0x00FF;
            crc ^= c;
            for (j = 0; j < 8; j++) {
                if ((crc & 0x0001) != 0) {
                    crc >>= 1;
                    crc ^= 0xA001;
                } else
                    crc >>= 1;
            }
        }
        return (crc);
    }

    int   nCRC16( byte[] buf,int Len) {
        char i;
        int j;
        char uchCRCHi;   //CRC高字节
        char uchCRCLo;   //CRC低字节


        /* CRC 高位字节值表*/
        char auchCRCHi[] = {
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
                0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
                0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
                0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
                0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
                0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
                0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
                0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
                0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
                0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
        } ;

        /* CRC 低位字节值表*/
        char auchCRCLo[] = {
                0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
                0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
                0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
                0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
                0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
                0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
                0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
                0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
                0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
                0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
                0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
                0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
                0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
                0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
                0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
                0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
                0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
                0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
                0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
                0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
                0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
                0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
                0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
                0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
                0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
                0x43, 0x83, 0x41, 0x81, 0x80, 0x40
        } ;
        uchCRCHi = 0xFF;
        uchCRCLo = 0xFF;
        for(j=0;j<Len;j++){
            i =(char)( uchCRCHi ^ ((int)(buf[j+3]&0xff)));
            uchCRCHi =(char)(uchCRCLo ^ auchCRCHi[i]);
            uchCRCLo = auchCRCLo[i];
        }
        return 1;
    }


    private  void testseekFeed(int myPosition,boolean onoff)
    {
        if(isdengpressed == 1) {
            int prog = onoff?50:0;
            if(seekBar1!=null)
                seekBar1.setProgress(prog);
            nneed = true;
            isdengpressed = 0;
        }
    }
    private  void  testFeed(int myPosition,boolean onff)
    {
        try {
            {

                //  if ((myPosition > 4)&&(myPosition < sPageJnodeArray.length + 1)) {

                if (myPosition > 0)  {
                    // if((sPageJpageno == 0)&&(myPosition ==4))
                    if ((sPageJ.pageno == 0) && (isdengpressed == 1)) {
                        testseekFeed(myPosition, onff);
                    }

                    View tmpView = frame.getChildAt(myPosition);
                    if((tmpView!=null)&&(tmpView instanceof  MeziView))
                    {
                        newm = (MeziView) frame.getChildAt(myPosition);
                    }


                    // String aaaa = newm.getId() + "|" + myPosition;
                    //  Log.e("feedTest", aaaa);

                    if (newm != null) {

                        newm.mRes = onff ? sPageJ.onArray[myPosition] : sPageJ.offArray[myPosition];
                        // newm.mRes = R.drawable.cbbm_television;
                        newm.repaint();
                        // newm.postInvalidate();
                        // newm.notify();
                    }
                }
            }
        }
        catch(Exception xx)
        {
            return;
        }

    }

    private  void  testzuoyFeed(int myPosition,boolean onff)
    {
        try {
            {

                //  if ((myPosition > 4)&&(myPosition < sPageJnodeArray.length + 1)) {

                if (myPosition > 0)  {


                    View tmpView = frame.getChildAt(myPosition);
                    if((tmpView!=null)&&(tmpView instanceof  MeziView))
                    {
                        newm = (MeziView) frame.getChildAt(myPosition);
                    }


                    // String aaaa = newm.getId() + "|" + myPosition;
                    //  Log.e("feedTest", aaaa);

                    if (newm != null) {

                        newm.mRes = onff ? sPageJ.onArray[myPosition] : sPageJ.offArray[myPosition];
                        // newm.mRes = R.drawable.cbbm_television;
                        newm.repaint();
                        // newm.postInvalidate();
                        // newm.notify();
                    }
                }
            }
        }
        catch(Exception xx)
        {
            return;
        }

    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {


            super.handleMessage(msg);
            // tv_msg.setText(content);
            // change GridView
            if(myowna!=null) {
                switch (msg.what) {


                    case 0:

                        // Toast mToast = Toast.makeText(MainActivityf.this, "请检查网络设置", 10);
                        //  mToast.show();

                        //  isSel = false;
                        break;
                    case 1://在收到消息时，对界面进行更新
                        // String fStatus = Integer.parseInt(msg.obj.toString());


                        try {
                            String myDevice = msg.getData().getString("feedDevice");
                            String myStatus = msg.getData().getString("feedStatus");
                            //  if (lType == 1) {
                            int myPosition = TransformUtils.findPosition(sPageJ.feedDArray, myDevice);
                            if (myPosition != -1) {
                                //  MeziView newm = new MeziView();
                                // MeziView  newm = (MeziView)frame.getChildAt(myPosition + 1);
                                //  MeziView  newm = getaddMezi(myPosition);
                                // testFeed(myPosition);
                                boolean fstt = myStatus.equals("0001") ? true : false;
                                testFeed(myPosition, fstt);
                                // Log.e("feegTag","myposition");

//                            if (myStatus.equals("0001")) {
//
//                                if(newm != null)
//                                {
//
//                                    newm.mRes = sPageJonArray[myPosition];
//                                }
//                               // ctlBtn[myPosition].setBackgroundResource(onArray[myPosition]);
//                            } else {
//                               // newm.mRes = sPageJoffArray[myPosition];
//
//                                if(newm != null)
//                                {
//
//                                    newm.mRes = sPageJonArray[myPosition];
//                                }
//                               // ctlBtn[myPosition].setBackgroundResource(offArray[myPosition]);
//                            }
                                //   }
//                    } else {
//                        int myPosition = TransformUtils.findPosition(rhArray, myDevice);
//                        if (myPosition != -1) {
//                            if (myStatus.equals("0001")) {
//                                ctlBtn[myPosition].setBackgroundResource(onArray[myPosition]);
//                            } else {
//                                ctlBtn[myPosition].setBackgroundResource(offArray[myPosition]);
//                            }
//                        }
                            }
                        } catch (Exception e) {
                            renew();
                        }

                      //  if (isSel > 0) isSel--;
                        //  isSel = false;
                        break;
                    case 2://在收到消息时，对界面进行更新
                        // String fStatus = Integer.parseInt(msg.obj.toString());


                        String myDevicex = msg.getData().getString("feedDevice");
                        String myStatusx = msg.getData().getString("feedStatus");
                         disv(myDevicex, myStatusx);
                        //  if (lType == 1) {
//                    int myPositionx = TransformUtils.findPosition(sPageJfeedDArray, myDevicex);
//                    if (myPositionx != -1) {
//                        //  MeziView newm = new MeziView();
//                        // MeziView  newm = (MeziView)frame.getChildAt(myPosition + 1);
//                        //  MeziView  newm = getaddMezi(myPosition);
//                        // testFeed(myPosition);
//                        boolean fstt = myStatusx.equals("0001") ? true:false;
//                        testFeed(myPositionx,fstt);
//                        Log.e("feegTag","myposition");
//
//
//                    }

                        //  isSel = false;
                        break;
                    case 3:
                        String[] jmpsrc = {"0", "1", "2", "3", "4", "5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","29","30",
                        "31","32","33","21","22","23","41","42","43","51","52","53","71","72","73","81","82","83","181","182",
                                "200", "201", "202", "203", "204", "205","206","207","208","209","210","211","212","213","214","215","216","217","218","219","229","230",
                                "231","232","233","221","222","223","241","242","243","251","252","253","271","272","273","281","282","283","381","382"
                        };

                        //通过 Bundle传过来


                        String fStatus = msg.obj.toString();
                        String myjmpposition = msg.getData().getString("jmppageno");

                        //  String myStatus = msg.getData().getString("feedStatus");

                        //  pagestatus.jmpPosition = Integer.parseInt(pagestatus.cmdArray[1]);
                        //  jmpPostion = pagestatus.jmpPosition;

                        //      if ((currentPage!=jmpPostion)&&(TransformUtils.IsInArray(src,jmpPostion + ""))) {

                      //  if ((currentPage != jmpPostion) && (TransformUtils.IsInArray(src, jmpPostion + ""))) {
                        if(myjmpposition != "") {
                            jmpPostion = Integer.parseInt(myjmpposition);
                            if (TransformUtils.IsInArray(jmpsrc, jmpPostion + "")) {
                                // refreshui(jmpPostion);
                                refreshui(jmpPostion);

                            }
                        }

                        reciteallui("");
                      //  if (isSel > 0) isSel--;
                        break;

                    case 4://在收到消息时，对界面进行更新
                        // String fStatus = Integer.parseInt(msg.obj.toString());
                        try {
                            String fStatusx = msg.obj.toString();
                            String myStatusa = "0001";
                            String myjmppositionx = msg.getData().getString("jmppageno");
                            int jmpPostionx = Integer.parseInt(myjmppositionx);

                            if (jmpPostionx != -1) {
                                myStatusa = sPageJ.feedMap.get(sPageJ.feedDArray[jmpPostionx]);
                                //  MeziView newm = new MeziView();
                                // MeziView  newm = (MeziView)frame.getChildAt(myPosition + 1);
                                //  MeziView  newm = getaddMezi(myPosition);
                                // testFeed(myPosition);
                                boolean fstt = myStatusa.equals("0001") ? false : true;
                                testFeed(jmpPostionx, fstt);
                                Log.e("feegTag4", myStatusa);

                            }
                        } catch (Exception ex) {
                            renew();
                        }

                        // isSel = false;
                        break;

                    case 5://在收到消息时，对界面进行更新
                        // String fStatus = Integer.parseInt(msg.obj.toString());
                        try {
                            String fStatusxy = msg.obj.toString();
                            String myStatusay = "0000";
                            String myjmppositionxy = msg.getData().getString("jmppageno");
                            int jmpPostionxy = Integer.parseInt(myjmppositionxy);
                            if (jmpPostionxy != -1) {
                                myStatusay = sPageJ.feedMap.get(sPageJ.feedDArray[jmpPostionxy]);
                                //  MeziView newm = new MeziView();
                                // MeziView  newm = (MeziView)frame.getChildAt(myPosition + 1);
                                //  MeziView  newm = getaddMezi(myPosition);
                                // testFeed(myPosition);
                                boolean fstt = myStatusay.equals("0001") ? true : false;
                                testFeed(jmpPostionxy, fstt);
                                Log.e("feegTag5", myStatusay);

                            }
                        } catch (Exception ex) {
                            renew();
                        }

                        // isSel = false;
                        break;

                    case 6://在收到消息时，对界面进行更新
                        // String fStatus = Integer.parseInt(msg.obj.toString());


                        String myDevicex6 = msg.getData().getString("feedDevice");
                        String myStatusx6 = msg.getData().getString("feedStatus");
        //                 dish(myDevicex6, myStatusx6);
                        //  if (lType == 1) {
//                    int myPositionx = TransformUtils.findPosition(sPageJfeedDArray, myDevicex);
//                    if (myPositionx != -1) {
//                        //  MeziView newm = new MeziView();
//                        // MeziView  newm = (MeziView)frame.getChildAt(myPosition + 1);
//                        //  MeziView  newm = getaddMezi(myPosition);
//                        // testFeed(myPosition);
//                        boolean fstt = myStatusx.equals("0001") ? true:false;
//                        testFeed(myPositionx,fstt);
//                        Log.e("feegTag","myposition");
//
//
//                    }

                        // isSel = false;
                        break;

                    case 7:
                        try {
                            // int ppp = seekBar.getProgress();
                            int which = msg.getData().getInt("whichno");


                            //  int ppp = seekBar.getProgress();
                            //  if (!slidera) {
//                            sendp(seekBar, which);
                            //  }
                        } catch (Exception ex) {
                            // return;
                            renew();
                        }

                        //   int jmpPostionxy = Integer.parseInt(myjmppositionxy);
                        //  sendp(seekBar,ppp);
                        // cmdOne = s
                        //msg.obj = "cmdOne";
                        //  Bundle bundle = new Bundle();
                        //    bundle.putString("jmppageno", cmdOne);
//                    bundle.putString("feedStatus", deviceStaus);


                     //   if (isSel > 0) isSel--;
                        break;


                    case 8://在收到消息时，对界面进行更新
                        // String fStatus = Integer.parseInt(msg.obj.toString());
                        // String which = msg.obj.toString();
                        Integer which = msg.getData().getInt("which");
                        boolean ifif = msg.getData().getBoolean("ifif");
                        testsoFeed(which, ifif);

                        // isSel = false;
                        break;
                    case 29://在收到消息时，对界面进行更新

                        String myDevice29 = msg.getData().getString("feedDevice");
                        String myStatuss29 = msg.getData().getString("feedStatus");

                         diswait(myDevice29, myStatuss29);

                        break;

                    case 9://在收到消息时，对界面进行更新
                        // String fStatus = Integer.parseInt(msg.obj.toString());


                        String myDevicea = msg.getData().getString("feedDevice");
                        String myStatussa = msg.getData().getString("feedStatus");
                        //  int myPosition = TransformUtils.findPosition(sPageJfeedDArray, myDevice);
                        //   if (myPosition != -1) {

                         disvol(myDevicea, myStatussa);
                        //  if (lType == 1) {
//                    int myPositionx = TransformUtils.findPosition(sPageJfeedDArray, myDevicex);
//                    if (myPositionx != -1) {
//                        //  MeziView newm = new MeziView();
//                        // MeziView  newm = (MeziView)frame.getChildAt(myPosition + 1);
//                        //  MeziView  newm = getaddMezi(myPosition);
//                        // testFeed(myPosition);
//                        boolean fstt = myStatusx.equals("0001") ? true:false;
//                        testFeed(myPositionx,fstt);
//                        Log.e("feegTag","myposition");
//
//
//                    }
                        break;
                    case 10://在收到消息时，对界面进行更新
                        // String fStatus = Integer.parseInt(msg.obj.toString());


                        String myDevice10= msg.getData().getString("feedDevice");
                        String myStatuss10 = msg.getData().getString("feedStatus");
                        //  int myPosition = TransformUtils.findPosition(sPageJfeedDArray, myDevice);
                        //   if (myPosition != -1) {

                        diszuoy(myDevice10, myStatuss10);
                        //  if (lType == 1) {
//                    int myPositionx = TransformUtils.findPosition(sPageJfeedDArray, myDevicex);
//                    if (myPositionx != -1) {
//                        //  MeziView newm = new MeziView();
//                        // MeziView  newm = (MeziView)frame.getChildAt(myPosition + 1);
//                        //  MeziView  newm = getaddMezi(myPosition);
//                        // testFeed(myPosition);
//                        boolean fstt = myStatusx.equals("0001") ? true:false;
//                        testFeed(myPositionx,fstt);
//                        Log.e("feegTag","myposition");
//
//
//                    }

                    case 11://在收到消息时，对界面进行更新
                        // String fStatus = Integer.parseInt(msg.obj.toString());


                        String myDevice11 = msg.getData().getString("feedDevice");
                        String myStatus11 = msg.getData().getString("feedStatus");
                        if(!("".equals(myDevice11)||"".equals(myStatus11))) {
                           // disfend(myDevice11, myStatus11);
                            disfend(myDevice11, myStatus11);
                        }

                        break;
                    case 12://在收到消息时，对界面进行更新
                        // String fStatus = Integer.parseInt(msg.obj.toString());


                        String myDevice12 = msg.getData().getString("feedDevice");
                        String myStatus12 = msg.getData().getString("feedStatus");
                        if(!("".equals(myDevice12)||"".equals(myStatus12))) {
                            diswend(myDevice12, myStatus12);
                           // diswend(myDevice11, myStatus11);
                        }

                        break;
                    default:
                        break;

                }
            }
        }
    };


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()){
            //获取触摸动作，如果ACTION_UP，计时开始。
            case MotionEvent.ACTION_UP:
            //  if(currentPage != 29)  countTimerView.start();
               // countTimerView.start();
           //   if(haveFinished)  timeStart();
               // countTimerView.
                timeStart();
                break;
            //否则其他动作计时取消
            default:
                if(countTimerView != null) {
                    countTimerView.cancel();
                }
                break;
        }
         return super.dispatchTouchEvent(ev);
       // return  true;
    }

    private  void testbtnFeed(int myPosition,boolean onff)
    {
        if(myPosition > -1) {
            Button newmx = (Button) frame.getChildAt(myPosition );


            String aaaa = newmx.getId() + "|" + myPosition;
            Log.e("feedTest", aaaa);

            if (newmx != null) {
                if(onff) {
                    newmx.setBackgroundResource(sPageJ.onArray[myPosition]);
                    // newm.mleft = convertWn(0);
                    //  newm.mtop = convertHn(0);
                    //  newm.lv = 92;
                    //  newm.mwidth = convertWn(78);
                    //   newm.mheight = convertHn(78);
                    //  newm.mRes  = onff ? sPageJ.onArray[myPosition] : sPageJ.offArray[myPosition];
//                    newm.ho = 27;
//                    newm.lv = 116;
//                    newm.la = 242;
//                    newm.li = 255;
//                     newm.mleft = (int) (newm.mleft - 10);
//                     newm.mtop = (int) (newm.mtop -10);
//                      // newm.lv = 92;
//                     newm.mwidth = (int) (newm.mwidth +20);
//                     newm.mheight = (int) (newm.mheight +20);
                }
                else
                {
                    // newm.mleft = convertWn(0);
                    //  newm.mtop = convertHn(0);
//                    newm.ho = 255;
//                    newm.lv = 255;
//                    newm.la = 255;
//                    newm.li = 255;
//                     newm.mleft =  (int) (newm.mleft + 10);
//                     newm.mtop = (int) (newm.mtop + 10);
//                     // newm.lv = 92;
//                     newm.mwidth = (int) (newm.mwidth -20);
//                     newm.mheight = (int) (newm.mheight -20);
                    //= convertWn(91);
                    //   newm.mheight = convertHn(91);
                    newmx.setBackgroundResource(sPageJ.offArray[myPosition]);
                }
                // newm.mRes = onff ? sPageJonArray[myPosition] : sPageJoffArray[myPosition];
                // newm.mRes = R.drawable.cbbm_television;
            //   newm.repaint();
                // newm.postInvalidate();
                // newm.notify();
            }
        }
        //  if(isSel>0)   isSel--;
    }

    private  void testsoFeed(int myPosition,boolean onff)
    {
        if(myPosition > 0) {
            newm = (MeziView) frame.getChildAt(myPosition );


            String aaaa = newm.getId() + "|" + myPosition;
            Log.e("feedTest", aaaa);

            if (newm != null) {
                if(onff) {
                    // newm.mleft = convertWn(0);
                    //  newm.mtop = convertHn(0);
                    //  newm.lv = 92;
                    //  newm.mwidth = convertWn(78);
                    //   newm.mheight = convertHn(78);
                    newm.mRes  = onff ? sPageJ.onArray[myPosition] : sPageJ.offArray[myPosition];
//                    newm.ho = 27;
//                    newm.lv = 116;
//                    newm.la = 242;
//                    newm.li = 255;
//                     newm.mleft = (int) (newm.mleft - 10);
//                     newm.mtop = (int) (newm.mtop -10);
//                      // newm.lv = 92;
//                     newm.mwidth = (int) (newm.mwidth +20);
//                     newm.mheight = (int) (newm.mheight +20);
                }
                else
                {
                    // newm.mleft = convertWn(0);
                    //  newm.mtop = convertHn(0);
//                    newm.ho = 255;
//                    newm.lv = 255;
//                    newm.la = 255;
//                    newm.li = 255;
//                     newm.mleft =  (int) (newm.mleft + 10);
//                     newm.mtop = (int) (newm.mtop + 10);
//                     // newm.lv = 92;
//                     newm.mwidth = (int) (newm.mwidth -20);
//                     newm.mheight = (int) (newm.mheight -20);
                    //= convertWn(91);
                    //   newm.mheight = convertHn(91);
                    newm.mRes  = onff ? sPageJ.onArray[myPosition] : sPageJ.offArray[myPosition];
                }
                // newm.mRes = onff ? sPageJonArray[myPosition] : sPageJoffArray[myPosition];
                // newm.mRes = R.drawable.cbbm_television;
                newm.repaint();
                // newm.postInvalidate();
                // newm.notify();
            }
        }
        //  if(isSel>0)   isSel--;
    }

    private void sendStart(String cmdOne)
    {
        String origin = "5AA50883192001001F"; //19E2
        String allCmdx = cmdheader;

        String tmpTmp = cmdOne;

        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
        StringBuffer allCmd = CRC16.crc16x(allCmdx);
        final String cmd = allCmd.substring(0, 22);
        boolean isSendst = false;
     //   isSendst = uartJnit.getInstance()
       //         .sendCmds(cmd);
       // SetLoopData(ComA,cmd);
        ComA.sendHex(cmd);
        Log.e("send start TAG", "send start " + cmd + " success");
//        if (isSendst) {
//
//
//            Log.e("send start TAG", "send start " + cmd + " success");
//        } else {
//            Log.e("send start TAG", "send start " + cmd + " failed!");
//        }

    }

    private static void sendStarttry(String cmdOne)
    {
//        String origin = "5AA50883192001001F"; //19E2
//        String allCmdx = cmdheader;
//
//        String tmpTmp = cmdOne;
//
//        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
//        StringBuffer allCmd = CRC16.crc16x(allCmdx);
//        final String cmd = allCmd.substring(0, 22);
//        boolean isSendst = false;
        //   isSendst = uartJnit.getInstance()
        //         .sendCmds(cmd);
        // SetLoopData(ComA,cmd);
        try {
            ComA.sendHex(cmdOne);
        }
        catch(Exception ex)
        {
            Log.e("send start TAG", "send start " + cmdOne + " failed");
        }

        Log.e("send start TAG", "send start " + cmdOne + " success");


    }
    private void psendStart(String cmdOne)
    {
        String origin = "5AA50883192001001F"; //19E2
        String allCmdx = cmdheader;

        String tmpTmp = cmdOne;

        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
        StringBuffer allCmd = CRC16.crc16x(allCmdx);
        final String cmd = allCmd.substring(0, 22);
        boolean isSendst = false;
    //    isSendst = uartJnit.getInstance().sendCmds(cmdOne);
        SetLoopData(ComA,cmd);
        if (isSendst) {


            Log.e("send start TAG", "send pstart " + cmdOne + " success");
        } else {
            Log.e("send start TAG", "send pstart " + cmdOne + " failed!");
        }

    }
    //声明定位回调监听器



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //84c95af2e8687ab694b8d5bf866cd3fb
        super.onCreate(savedInstanceState);

        setContentView(R.layout.layout_start);
        myowna =  new WeakReference(this);
        frameall = (myFrameLayout) findViewById(R.id.gridlayoutall);

        frame = (myFrameLayout) findViewById(R.id.gridlayoutx);
        frameseond = (myFrameLayout) findViewById(R.id.gridlayouts);
       // Point mysize = getmySize(this);
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.a1);
        try {
          //  if (!)
//            initpLocation();
//            startLocation();
          //  saveBmp2Gallery(this, bmp, "上海捷豹");
            if(TransformUtils.isRepeat(sPageJ.tmpAlla))
            {
                Log.e("repeat"," repeat");
            }
            else
            {
                Log.e("no repeat","go on");
            }
        }
        catch(Exception ex)
        {

        }

        // sPageJsetfeeds();
//        IntentFilter filter = new IntentFilter();
//        filter.addAction(Intent.ACTION_SCREEN_ON);
//        filter.addAction(Intent.ACTION_SCREEN_OFF);
//        //filter.addAction(android.intent.action.USER_PRESENT);
//        mReceiver = new LockScreenReceiver();
//        registerReceiver(mReceiver, filter);

       // refreshui(0);

        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

       // showSystemUI();
       // showStatusBar();


        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

      //  int screenWidth = dm.widthPixels;

     //   int screenHeight = dm.heightPixels;

        //this.addContentView();

       // showStatusBar();
      //  makeStatusBarTransparent(this);
       // setStatusBarFullTransparent();
      //  setFitSystemWindow(false);
      //  hideBottomUIMenu();

        uiSwitch = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1) {
                    Bundle bundle = msg.getData();
                    int  curpos = bundle.getInt("which");
                    boolean ifif = bundle.getBoolean("ifif");
//                    sPageJ.m.setBackgroundResource(R.drawable.ic_launcher_foreground);
                     testbtnFeed(curpos,ifif);
                   // testsoFeed(curpos,ifif);
                }
                else if (msg.what == 0) {
                    Bundle bundle = msg.getData();
                    int  curpos = bundle.getInt("which");
                    boolean ifif = bundle.getBoolean("ifif");
                  //  testsoFeed(curpos,ifif);
//                    sPageJ.m.setBackgroundResource(R.drawable.ic_launcher_foreground);
                     testbtnFeed(curpos,ifif);
                }
                // mButton.setBackgroundResource(R.drawable.ic_launcher_background);
            }

        };

         hideBottomUIMenu();

//        ComA = new SerialControl();
////
//        try {
//            ComA.open();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        DispQueue = new DispQueueThread();
//
//        //   ComBean cm  = new ComBean("dev/tt")
//        //  DispQueue.QueueList.add()
//        DispQueue.start();

//        mLocationClient = new AMapLocationClient(getApplicationContext());
//        //设置定位回调监听
//        mLocationClient.setLocationListener(mLocationListener);
//        //初始化AMapLocationClientOption对象
//        mLocationOption = new AMapLocationClientOption();
//        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//        // mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Device_Sensors);
//        mLocationClient.setLocationOption(mLocationOption);



        //初始化定位

//        initpView();
//
//        inittView();

        init();
    }
//   public AMapLocationListener mLocationListener = new AMapLocationListener() {
//        @Override
//        public void onLocationChanged(AMapLocation aMapLocation) {
//            // aslNum.setText(aMapLocation.getAltitude() + "米");
//            System.out.println(aMapLocation.getAltitude() + "米");
//            //   addressTextView.setText(aMapLocation.getProvince() + "\n" + aMapLocation.getCity() + " " + aMapLocation.getDistrict());
//            //  if (isFristWeather) {
//            //       isFristWeather = false;
//            //  addresscode = aMapLocation.getAdCode();
//
//            //  initweather(addresscode);
//            //        }
//        }
//    };

    class MyConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
           // Log.i(TAG, "onServiceConnected");
            mBinder = (MusicService.MyBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
           // Log.i(TAG, "onServiceDisconnected");
        }
    }


    private void rotatexo(ImageView Valueb,double d)
    {
        Valueb.setPivotX(convertWn(197));
        Valueb.setPivotY(convertHn(297));
        Valueb.setRotation((float)d);
    }

    private void disinito(double hh ,double mm, double ass, double ss,long mill)
    {
        //  iv_needle_second .setRotation(270);
        Log.e("changesss",mill + "#" + ss + "#" + mm + "#" + hh);

        iv_needle_minute .setRotation((float)(mm + ass/60f)*6);


        iv_needle_hour .setRotation((float)(hh + mm/60f)*30);

    }

    private void disinit(double hh ,double mm, double ss)
    {
        //  iv_needle_second .setRotation(270);
//        iv_needle_second .setRotation((float)(ss-15)*6);
//
//        iv_needle_minute .setRotation((float)(mm-15)*6);
//
//
//        iv_needle_hour .setRotation((float)(hh-3)*30);
       // iv_needle_second .setRotation((float)(ss)*6);

        iv_needle_minute .setRotation((float)(mm)*6);


       iv_needle_hour .setRotation((float)(hh)*30);

    }

    private void disinitx(double hh ,double mm, double ss)
    {
        //  iv_needle_second .setRotation(270);
        iv_needle_second .setRotation((float)(ss*6));


        iv_needle_minute .setRotation((float)(mm*6));


        iv_needle_hour .setRotation((float)(hh*30));
        //  rotatexo(iv_needle_hour,270);
    }


    private void dispt(int h,int m,int s)
    {
        // Valueb.setPivotX(convertWn(x+w/2));
        //  Valueb.setPivotY(convertHn(y+h/2));
        // Valueb.setRotation(d);

        //   rotatexo(iv_needle_second,270);
        //   rotatexo(iv_needle_second,s*6);
        iv_needle_second .setRotation(270);
        iv_needle_second .setRotation(s*30);

        //   rotatexo(iv_needle_minute,270);
        //  rotatexo(iv_needle_minute,(m+s/60.0)*6);
        iv_needle_minute .setRotation(270);
        iv_needle_minute .setRotation((m+s/60)*30);

        // rotatexo(iv_needle_hour,270);
        //  rotatexo(iv_needle_hour,(h+m/60.0+s/3600.0)*6);
        iv_needle_hour .setRotation(270);
        iv_needle_hour .setRotation((h+m/60+s/3600)*30);

    }

    private void oldtimecyc()
    {
        Calendar calendar = Calendar.getInstance();
/*
        allsecond = (allsecond + 1) % (24 * 3600 * 5);
        int tmpsecond = allsecond / 5;
        secondv = initsecondv + tmpsecond % 60;
        minutev = initminutev + (tmpsecond / 60);
        hourv = inithourv + (tmpsecond / 3600);
      //  secondv = tmpsecond % 60;
     //   minutev =  (tmpsecond / 60);
    //    hourv =  (tmpsecond / 3600);
        //hourv=calendar.get(Calendar.HOUR);//获取当前日  HOUR_OF_DAY-24小时制
        //             minutev=calendar.get(Calendar.MINUTE);//获取当前分
        //             secondv=calendar.get(Calendar.SECOND);//获取当前秒
        //            Log.e("ymd = ",ymd + hourv + ":" + minutev + ":" + secondv);
        //          //  dispt(hourv,minutev,secondv);
        Log.e("changes",allsecond + "#" + secondv + "#" + minutev + "#" + hourv);
        disinit(hourv, minutev, secondv);
*/

        //  if (allsecond > 1500 - 10) {

        inithourv = calendar.get(Calendar.HOUR);//获取当前日  HOUR_OF_DAY-24小时制
        initminutev = calendar.get(Calendar.MINUTE);//获取当前分
        initsecondv = calendar.get(Calendar.SECOND);//获取当前秒
        long curmill = calendar.get(Calendar.MILLISECOND);

        double tmps = initsecondv - lastseconds;
        //   if((tmps < 1.0) && (curmill > 800.0)) {
        double tmpnext = lastseconds;
        //   boolean bool1 = (tmps < 1.0)&&(curmill > 750.0);
        //      //  boolean bool2 = ((curmill < 200) && (tmps > 1.0));
        //      //  if(bool1 || bool2) {
        boolean bool1 = (curmill > 800.0);
        //  boolean bool2 = ((curmill < 200) && (tmps > 1.0));
        //   if(bool1) {
        //  tmpnext = (lastseconds + 1) % 60;
        disinito(inithourv, initminutev,initsecondv, tmpnext, curmill);
        lastseconds = tmpnext;

//        Date date =calendar.getTime();
//        Long time=date.getTime();//年月日的毫秒值 日期比较大小时可以比较毫秒值
//        SimpleDateFormat formatter = new SimpleDateFormat ("yyyy.MM.dd");
//        String ymd=formatter.format(time);//yyyy-MM-dd
//       // tv_date.setText(ymd);
//        tdView.setText(ymd);
         settime();
        //   }
        //  disinit(inithourv, initminutev, initsecondv);
        //    }
        //   lastseconds = initsecondv;
        //lastseconds = tmpnext;

        //   allsecond = 0;
        //  }
        //   dispt(hour
    }


    @Override
    protected void onResume(){
        super.onResume();
        //initpLocation();
        initpLocation();
        startLocation();
        onlyone = 0;
        lonlyone = 0;
         allappsonlyone = 0;
        exitapponlyone = 0;
          pauseonlyone = 0;
          lastsonlyone = 0;
         nextsonlyonce = 0;

//        AudioManager audio = (AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
//
//
//        ismute = audio.isMusicActive();

      //  if(ismute) {
//            initView();
//            if (mBinder != null) {
//               // mBinder.pre();
//                String songname = mBinder.getName() + mBinder.getCurrenPostion();
//                String tmp = songname;
//            }
     //   }

       //AudioPlaybackConfiguration apc = audio.getActivePlaybackConfigurations();


//        int result = mAm.requestAudioFocus(mListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
//
//        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
//            Log.i(TAG, "requestAudioFocus successfully.");
//
//            // Start playback.
//            player.start();
//        } else {
//            Log.e(TAG, "requestAudioFocus failed.");
//        }

//        if(fd==0) {
//
//            fd = uartJnit.getInstance().fd;
//        }

//        if (!sPageJ.isActive) {
//            //   app 从后台唤醒，进入前台
//
//            sPageJ.isActive = true;
//        }
//
//        if(sPageJ.isActive) {
//
//
//        }

        //Point mysize = getmySize(this);


        try {
            sPageJ.setfeeds();
            refreshui(currentPage);



            String allCmdx = cmdheader;

            String tmpTmp = "C1200009";
            // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
            allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
            StringBuffer allCmd = CRC16.crc16x(allCmdx);


            DisplayMetrics dm = new DisplayMetrics();

            getWindowManager().getDefaultDisplay().getMetrics(dm);



           // int jieh = getNavigationBarHeight(this);
//        int screenWidth = dm.widthPixels;
//
//        int screenHeight = dm.heightPixels - jieh;
         //   int screenWidth = sPageJ.pwidth;
          //  int screenHeight = sPageJ.pheight;

//            testtView = new TextView(this);
//
//            testtView.setPadding(20, 0, 20, 0);
//            testtView.setText("this is used for testing");
//            testtView.setTextColor(getResources().getColor(R.color.colorAccent));
//            testtView.setTextSize(18);
//
//
//            LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
//            testtView.setLayoutParams(params);
//            this.addContentView(testtView,params);
//            testtView.setVisibility(View.INVISIBLE);
            //  AsyncTaskRunner runner = new AsyncTaskRunner();
            //String sleepTime = "10:0000000123456";
            //  runner.execute();
            // makeStatusBarTransparent(this);

            hideBottomUIMenu();

            reciteallui("");
//            try {
//                if(!hasStarted) {
//                  aress();
//                  //  Message newmm = Message.obtain();
//                 //   newmm.what = 1;
//                 //   xxHandler.sendEmptyMessage(newmm.what);
//                    //  AsyncTaskRunner runner = new AsyncTaskRunner();
//                    //String sleepTime = "10:0000000123456";
//                    //   runner.execute();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }

           // ComA = new SerialControl();

          //   ComA.open();
//            DispQueue = new DispQueueThread();
//
//         //   ComBean cm  = new ComBean("dev/tt")
//          //  DispQueue.QueueList.add()
//           DispQueue.start();
         //   AssistData = getAssistData();
          //  setControls();


         //   init();
            // BC 10 00 00
            //  sendStart("BC100000");

            DispTimeQueue = new DispTimeThread();
            DispTimeQueue.start();;

            ComA = new SerialControl();

            ComA.open();
            DispQueue = new DispQueueThread();

            // //   ComBean cm  = new ComBean("dev/tt")
            //   //  DispQueue.QueueList.add()
            DispQueue.start();

            //  setInitCmd(0);
            setInitcmd(29) ;
        }
        catch(Exception ex)
        {
            renew();
        }






//        String sscode = sgetcode();
//        String ssloc = sgetarea();
//        if(locView != null)
//        {
//            locView.setText(ssloc);
//            initweather(sPageJ.initacode);
//        }

        //timeStart();
    }

    @Override
    protected void onPause() {
        ;
            super.onPause();
        countTimerView.cancel();

            // If the screen is off then the device has been locked

//            PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
//
//            boolean isScreenOn;
//
//            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
//
//                isScreenOn = powerManager.isInteractive();
//
//            } else {
//
//                isScreenOn = powerManager.isScreenOn();
//
//            }



//            if (!isScreenOn) {
//
//                Log.e("is off ","start");
//              //  Instrumentation mInst = new Instrumentation();
//              //  mInst.sendKeyDownUpSync(KeyEvent.KEYCODE_POWER);
//
//                startActivity.this.runOnUiThread(new Runnable() {
//                                                     @Override
//                                                     public void run() {
//                                                         try {
//
//                                                           //  String keyCommand = "input keyevent " + KeyEvent.KEYCODE_POWER;
//                                                             String keyCommand = "input keyevent " + KeyEvent.KEYCODE_WAKEUP;
//                                                             Runtime runtime = Runtime.getRuntime();
//
//                                                             Process proc = runtime.exec(keyCommand);
//
//                                                         } catch (IOException e) {
//                                                             Log.e("is off ", "fail send");
//                                                         }
//                                                         Log.e("is off ", "power");
//                                                     }
//                                                 });
              //  mInst.sendKeyDownUpSync(KeyEvent.KEYCODE_WAKEUP);
//                try{
//
//                    String keyCommand = "input keyevent " + KeyEvent.KEYCODE_WAKEUP;
//
//                    Runtime runtime = Runtime.getRuntime();
//
//                    Process proc = runtime.exec(keyCommand);
//
//                } catch(IOException e){
//
//                }

//                try{
//
//                    String keyCommand = "input keyevent " + KeyEvent.KEYCODE_VOLUME_UP;
//
//                    Runtime runtime = Runtime.getRuntime();
//
//                    Process proc = runtime.exec(keyCommand);
//
//                } catch(IOException e){
//





            }





    private void timeStart(){
     //   haveFinished = false;
//         new Handler(getMainLooper()).post(new Runnable() {
//            @Override
//            public void run() {
//                countTimerView.start();
//                haveFinished = false;
//            }
//        });
        countTimerView.start();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                countTimerView.start();
//            }
//        }).start();
    }

    private void init() {
        //初始化CountTimer，设置倒计时为2分钟。
        countTimerView=new CountTimer(sPageJ.interval * 1000,1000,startActivity.this);
    }

    public   String PREFS_NAME = "myipp";

    private   String acode = "";
    private String area = "";

    public  String getacode() {
        return acode;
    }
    public void ssetMyip(String acode,String area){
        SharedPreferences userInfo = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = userInfo.edit();//获取Editor
        //得到Editor后，写入需要保存的数据
        editor.putString("acode", acode);
        editor.putString("area", area);
        // editor.putInt("age", 20);
        editor.commit();//提交修改
        //Log.i(TAG, "保存用户信息成功");
    }
    private String sgetcode(){
      //  String tmpip = "";
        SharedPreferences userInfo = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        String lastacode = userInfo.getString("acode", sPageJ.initacode);//读取username
        // int age = userInfo.getInt("age", 0);//读取age
        //   Log.i(TAG, "读取用户信息");
        //  Log.i(TAG, "username:" + username + "， age:" + age);
        return lastacode;
    }

    private String sgetarea(){
        String tmpip = "";
        SharedPreferences userInfo = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        String lastacode = userInfo.getString("area", sPageJ.initloc);//读取username
        // int age = userInfo.getInt("age", 0);//读取age
        //   Log.i(TAG, "读取用户信息");
        //  Log.i(TAG, "username:" + username + "， age:" + age);
        return lastacode;
    }
//    @Override
//    protected void onResume() {
//
//
//        super.onResume();
//        hideBottomUIMenu();
//
//    }

    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    public  void aress() throws IOException {

        hasStarted = true;
        try {

            if(serverThread == null) {

                serverThread = new ServerThread();
                new Thread(serverThread).run();


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void hideSystemUI() {
        getWindow().getDecorView().setSystemUiVisibility(4102);
        getWindow().setFlags(1024, 1024);
    }

//    private View contentViewGroup;
//
//    protected void setFitSystemWindow(boolean fitSystemWindow) {
//        if (contentViewGroup == null) {
//            contentViewGroup = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
//        }
//        contentViewGroup.setFitsSystemWindows(fitSystemWindow);
//    }
    protected void setStatusBarFullTransparent() {
        if (Build.VERSION.SDK_INT >= 21) {//21表示5.0
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= 19) {//19表示4.4
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //虚拟键盘也透明
            //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }

    public static void makeStatusBarTransparent(Activity activity) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            return;
        }
        Window window = activity.getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            int option = window.getDecorView().getSystemUiVisibility() | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
            window.getDecorView().setSystemUiVisibility(option);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }




//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            //Toast.makeText(MainActivity.this,"BACK key").show();
//
//            callMenu.toast(MainActivity.this,"Back key call");
//            callMenu.closeAPk("com.kugou.android",MainActivity.this);
//           // callMenu.kill("com.kugou.android");
//        }
//        return  true;
//        //return super.onKeyDown(keyCode, event);
//    }


    private void showStatusBar() {
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags &= ~WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setAttributes(attrs);
    }

    public void removeAll()
    {
        if (frame != null) {
            removeclock();
            frame.removeAllViews();

            frame.invalidate();
        }
        maxC = 0;
    }

    private void SetLoopData(SerialHelper ComPort,String sLoopData){

           // ComPort.setTxtLoopData(sLoopData);

            ComPort.setHexLoopData(sLoopData);

    }
    void refreshui()
    {


        removeAll();
        pagestatus.setInit(0);

        currentPage = sPageJ.pageno;

      //  JBtnView mezi = new JBtnView(startActivity.this);
        MeziView mezi = new MeziView(startActivity.this);


        mezi.bitmapX = 100;
        mezi.bitmapY = 0;
        mezi.mleft = convertW(0);
        mezi.mtop = convertH(0);
        mezi.mwidth = convertW(10);
        mezi.mheight = convertH(10);
        mezi.mRes = R.drawable.b1_off;
        mezi.type = 1;
        mezi.setClickable(true);


        mezi.setId(0);
        // frame.setTag(allCmd.toString());
        mezi.setOnTouchListener(new startActivity.TouchListenerx());

        frame.addView(mezi,-1);
        //  frame.setBackgroundResource(sPageJpageback);
        //   frame.setBackgroundResource(R.drawable.a6);
        // frame.addView(mezi,0);
        // frame.invalidate();

        addmezis();

       // if(keyy == 0) {
         //   createSeek31();
           // createSeek32();
            // createbtns();
       // }


    }

//
//    @Override
//    protected void onDestroy() {
//        // uartJni.close(fd);
//       // uartJnit.sclose();
//        super.onDestroy();
//    }

    public int convertW(int oldx) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int screenWidth = dm.widthPixels;

     //   int screenHeight = dm.heightPixels;

        screenWidth = sPageJ.pwidth;
        int newx =( oldx * screenWidth) / 1024;

        return newx;

    }


    private int getNavigationBarHeight1(Context context, int orientation) {

        Resources resources = context.getResources();



        int id = resources.getIdentifier(

                orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_height_landscape",

                "dimen", "android");

        if (id > 0) {

            return resources.getDimensionPixelSize(id);

        }

        return 0;

    }
    public void getAppViewHeight(){
        //屏幕
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        //应用区域
        Rect outRect1 = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect1);
        int statusBar = dm.heightPixels - outRect1.height();  //状态栏高度=屏幕高度-应用区域高度
        //  Log.e(TAG, "应用区高度:" + statusBar);
    }

    public   int  getStatusBarHeightByReflect() {
        int statusBarHeight2 = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height")
                    .get(object).toString());
            statusBarHeight2 = getResources().getDimensionPixelSize(height);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusBarHeight2;
        // Log.e(TAG, "状态栏高度-反射方式：" + statusBarHeight2);
    }
    public static Point getAppUsableScreenSize(Context context) {

        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

        Display display = windowManager.getDefaultDisplay();

        Point size = new Point();

        display.getSize(size);
        //  sPageJ.pwidth = size.x;
        //  sPageJ.pheight = size.y;

        return size;

    }



    public static Point getRealScreenSize(Context context) {

        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

        Display display = windowManager.getDefaultDisplay();

        Point size = new Point();



        if (Build.VERSION.SDK_INT >= 17) {

            display.getRealSize(size);

        } else if (Build.VERSION.SDK_INT >= 14) {

            try {

                size.x = (Integer) Display.class.getMethod("getRawWidth").invoke(display);

                size.y = (Integer) Display.class.getMethod("getRawHeight").invoke(display);

            } catch (IllegalAccessException e) {} catch (InvocationTargetException e) {} catch (NoSuchMethodException e) {}

        }




        return size;

    }




    public int getNavBarHeight2(Context c) {

        int result = 0;

        boolean hasMenuKey = ViewConfiguration.get(c).hasPermanentMenuKey();

        boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);



        if(!hasMenuKey && !hasBackKey) {

            //The device has a navigation bar

            Resources resources = c.getResources();



            int orientation = resources.getConfiguration().orientation;

            int resourceId;

        //    if (isTablet(c)){

                resourceId = resources.getIdentifier(orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_height_landscape", "dimen", "android");

//            }  else {
//
//                resourceId = resources.getIdentifier(orientation == Configuration.ORIENTATION_PORTRAIT ? "navigation_bar_height" : "navigation_bar_width", "dimen", "android");
//
//            }



            if (resourceId > 0) {

                return resources.getDimensionPixelSize(resourceId);

            }

        }

        return result;

    }
//    public Point getmySize(Context context) {
//
//        Point appUsableSize = getAppUsableScreenSize(context);
//
//        Point realScreenSize = getRealScreenSize(context);
//
//        int topsizeyy = getStatusBarHeightByReflect();
//        int  botsizeyy = getNavigationBarHeight1(this, Configuration.ORIENTATION_PORTRAIT);
//        int allminus = 0;
//
//        Point retpoint = null;
//
//        Rect outRect1 = new Rect();
//        try {
//            ((Activity) context).getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect1);
//        } catch (ClassCastException e) {
//            e.printStackTrace();
//
//        }
//        int activityHeight = outRect1.height();
//        int activityWidth = outRect1.width();
//
//        // if(!isTabletDevice()) {
////        if (appUsableSize.x < realScreenSize.x - 5) {
////            //   int  innerbottom = getNavigationBarHeight1(this,Configuration.ORIENTATION_PORTRAIT);
////
////            sPageJ.pwidth = realScreenSize.x - topsizeyy;
////            sPageJ.pheight = appUsableSize.y;
////        }
////
////        if (appUsableSize.y < realScreenSize.y - 5) {
//            // int  innerbottom = getNavigationBarHeight1(this,Configuration.ORIENTATION_PORTRAIT);
//
//            sPageJ.pwidth = realScreenSize.x;
//
//            sPageJ.pheight =realScreenSize.y;
//            ;
//      //  }
//        //     }
////        else
////        {
////            if (appUsableSize.x < realScreenSize.x - 5) {
////                   int  innerbottom = getNavigationBarHeight1(this,Configuration.ORIENTATION_PORTRAIT);
////              //  int  botsizeyy = getNavigationBarHeight1(this,Configuration.ORIENTATION_PORTRAIT);
////                sPageJ.pwidth = realScreenSize.x - innerbottom ;
////                sPageJ.pheight = realScreenSize.y;
////            }
////
////            if (appUsableSize.y < realScreenSize.y - 5) {
////                 int  innerbottom = getNavigationBarHeight1(this,Configuration.ORIENTATION_LANDSCAPE);
////
////                sPageJ.pwidth = realScreenSize.x;
////
////                sPageJ.pheight = realScreenSize.y - innerbottom;
////                ;
////            }
////        }
//
//        // navigation bar on the side
////        if (appUsableSize.x < realScreenSize.x - 5) {
////        if ( activityWidth <  appUsableSize.x - 5) {
////             int topsize = getStatusBarHeightByReflect();
////            // retpoint = new Point(realScreenSize.x - appUsableSize.x, appUsableSize.y);
////            allminus = getNavigationBarHeight1(this, Configuration.ORIENTATION_PORTRAIT);
////            sPageJ.pwidth = appUsableSize.x -topsize ;
////            sPageJ.pheight = appUsableSize.y;
////        }
////        else
////        {
////            int topsize = getStatusBarHeightByReflect();
////            allminus = getNavigationBarHeight1(this, Configuration.ORIENTATION_PORTRAIT);
////            sPageJ.pwidth = appUsableSize.x ;
////            sPageJ.pheight = appUsableSize.y;
////        }
////        }
////
////
////
////
////       // int remainHeight =realScreenSize.x - botsizeyy;
////
////
////        // navigation bar at the bottom
////
////        if (appUsableSize.y < realScreenSize.y - 5) {
////            if ( activityHeight <  appUsableSize.y - 5) {
////                retpoint = new Point(appUsableSize.x, realScreenSize.y - appUsableSize.y);
////                int topsize = getStatusBarHeightByReflect();
////                allminus = getNavigationBarHeight1(this, Configuration.ORIENTATION_LANDSCAPE);
////                sPageJ.pheight = appUsableSize.y  ;
////                sPageJ.pwidth = appUsableSize.x;
////            }
////            else
////            {
////                retpoint = new Point(appUsableSize.x, realScreenSize.y - appUsableSize.y);
////                allminus = getNavigationBarHeight1(this, Configuration.ORIENTATION_LANDSCAPE);
////                int topsize = getStatusBarHeightByReflect();
////                sPageJ.pheight = appUsableSize.y -;
////                sPageJ.pwidth = appUsableSize.x;
////            }
////
////        }
////
//
//
//
//        // navigation bar is not present
//
//        //   sPageJ.pwidth = retpoint.
//        return retpoint;
//
//    }
public   Point getmySize(Context context) {

    Point appUsableSize = getAppUsableScreenSize(context);

    Point realScreenSize = getRealScreenSize(context);

    int topsizeyy = getStatusBarHeightByReflect();
    int  botsizeyy = getNavigationBarHeight1(this,Configuration.ORIENTATION_PORTRAIT);
    int allminus = 0;

    Point retpoint = null;

    Rect outRect1 = new Rect();
    try {
        ((Activity) context).getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect1);
    } catch (ClassCastException e) {
        e.printStackTrace();

    }
    int activityHeight = outRect1.height();
    int activityWidth = outRect1.width();

    // if(!isTabletDevice()) {
    if (appUsableSize.x + botsizeyy < realScreenSize.x + 5 ) {
        int  innerbottom = getNavigationBarHeight1(this,Configuration.ORIENTATION_PORTRAIT);

        // sPageJ.pwidth = realScreenSize.x - topsizeyy;
        sPageJ.pwidth = appUsableSize.x + botsizeyy;
        sPageJ.pheight =  realScreenSize.y;
    }
    else
    {
        sPageJ.pwidth = appUsableSize.x ;
        sPageJ.pheight =  realScreenSize.y;
    }

    if (appUsableSize.y < realScreenSize.y - 5) {
        // int  innerbottom = getNavigationBarHeight1(this,Configuration.ORIENTATION_PORTRAIT);

        sPageJ.pwidth = realScreenSize.x;
        sPageJ.pheight = realScreenSize.y;
        //  sPageJ.pheight = realScreenSize.y - topsizeyy;

    }

    // whoisl(realScreenSize);
    //  sPageJ.pwidth = retpoint.x;
    // sPageJ.pheight = retpoint.y;

    //   sPageJ.pwidth = sPageJ.pwidth - 114;

    //sPageJ.pheight = 980;
    //     }
//        else
//        {
//            if (appUsableSize.x < realScreenSize.x - 5) {
//                   int  innerbottom = getNavigationBarHeight1(this,Configuration.ORIENTATION_PORTRAIT);
//              //  int  botsizeyy = getNavigationBarHeight1(this,Configuration.ORIENTATION_PORTRAIT);
//                sPageJ.pwidth = realScreenSize.x - innerbottom ;
//                sPageJ.pheight = realScreenSize.y;
//            }
//
//            if (appUsableSize.y < realScreenSize.y - 5) {
//                 int  innerbottom = getNavigationBarHeight1(this,Configuration.ORIENTATION_LANDSCAPE);
//
//                sPageJ.pwidth = realScreenSize.x;
//
//                sPageJ.pheight = realScreenSize.y - innerbottom;
//                ;
//            }
//        }

    // navigation bar on the side
//        if (appUsableSize.x < realScreenSize.x - 5) {
//        if ( activityWidth <  appUsableSize.x - 5) {
//             int topsize = getStatusBarHeightByReflect();
//            // retpoint = new Point(realScreenSize.x - appUsableSize.x, appUsableSize.y);
//            allminus = getNavigationBarHeight1(this, Configuration.ORIENTATION_PORTRAIT);
//            sPageJ.pwidth = appUsableSize.x -topsize ;
//            sPageJ.pheight = appUsableSize.y;
//        }
//        else
//        {
//            int topsize = getStatusBarHeightByReflect();
//            allminus = getNavigationBarHeight1(this, Configuration.ORIENTATION_PORTRAIT);
//            sPageJ.pwidth = appUsableSize.x ;
//            sPageJ.pheight = appUsableSize.y;
//        }
//        }
//
//
//
//
//       // int remainHeight =realScreenSize.x - botsizeyy;
//
//
//        // navigation bar at the bottom
//
//        if (appUsableSize.y < realScreenSize.y - 5) {
//            if ( activityHeight <  appUsableSize.y - 5) {
//                retpoint = new Point(appUsableSize.x, realScreenSize.y - appUsableSize.y);
//                int topsize = getStatusBarHeightByReflect();
//                allminus = getNavigationBarHeight1(this, Configuration.ORIENTATION_LANDSCAPE);
//                sPageJ.pheight = appUsableSize.y  ;
//                sPageJ.pwidth = appUsableSize.x;
//            }
//            else
//            {
//                retpoint = new Point(appUsableSize.x, realScreenSize.y - appUsableSize.y);
//                allminus = getNavigationBarHeight1(this, Configuration.ORIENTATION_LANDSCAPE);
//                int topsize = getStatusBarHeightByReflect();
//                sPageJ.pheight = appUsableSize.y -;
//                sPageJ.pwidth = appUsableSize.x;
//            }
//
//        }
//



    // navigation bar is not present

    //   sPageJ.pwidth = retpoint.
    return retpoint;

}
    public static String toHex(byte[] buffer,int read_count) {
        StringBuffer sb = new StringBuffer(read_count * 2);
        for (int i = 0; i < read_count; i++) {
            sb.append(Character.forDigit((buffer[i] & 240) >> 4, 16));
            sb.append(Character.forDigit(buffer[i] & 15, 16));
        }
        return sb.toString();
    }

    public  Rect convertRect(Rect old)
    {
        return  new Rect(convertW(old.left),convertH(old.top),convertW(old.right),convertH(old.bottom));
    }
    public int convertH(int old) {
        DisplayMetrics dm = new DisplayMetrics();
//
         getWindowManager().getDefaultDisplay().getMetrics(dm);
//
//        int screenWidth = dm.widthPixels;

        int jieh = getNavigationBarHeight(this);
//
        int screenHeight = dm.heightPixels + jieh;


        screenHeight = sPageJ.pheight;
//
        int newx = (old * screenHeight) / 600;

        return newx;

    }

    protected int rconvertW(int oldx) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int screenWidth = dm.widthPixels;

        int screenHeight = dm.heightPixels;

        int newx = (oldx *  1024) / screenWidth;

        return newx;

    }



    private int getNavigationBarHeight(Activity thisa) {
        Resources resources = thisa.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height","dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
       // height = 0;
        return height;
    }

    public int convertHn(int old) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);


        int jieh = getNavigationBarHeight(this);
        int screenWidthx = dm.widthPixels;
        int screenHeighty = dm.heightPixels;

//        int screenWidth = dm.widthPixels;
//
        int screenHeightyy= screenHeighty + jieh;
      //  int screenWidth = sPageJ.pwidth;
         screenHeightyy = sPageJ.pheight;

        int newx = (old * screenHeightyy) / 600;

        return newx;

    }


    public int convertWn(int oldx) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);




     //   int jieh = getNavigationBarHeight(this);
        int screenWidth = dm.widthPixels;
//
//        int screenHeight = dm.heightPixels - jieh;
          screenWidth = sPageJ.pwidth;
      //   int screenHeight = sPageJ.pheight;

        int newx = oldx * screenWidth / 1024;

        return newx;

    }



    public String getNextCmd(int sseq,int interno)
    {
        String result = "";

        switch(sseq)
        {

            case 0:
                result = "D1B000" + TransformUtils.dectostr(interno);
                break;

            case 1:
                result = "EE0500" + TransformUtils.dectostr(interno);
                break;
            case 2:
                result = "EE0600" + TransformUtils.dectostr(interno);
                break;
            default:
                break;

        }
        return result;
    }
    public void pslidersend(String cmdx)
    {
        //String cmdx = sPageJsliderCmd[seekno][sseq];
        // String tmpTmp = "C1200009";
        String cmdheader = "5AA50883";
        String feedheader = "5AA5";
        String allCmdx = cmdheader;
        String tmpTmp = cmdx;
        // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
        StringBuffer allCmd = CRC16.crc16x(allCmdx);
        final String cmd = allCmd.substring(0, 22);
        // String crcString = "83192001001F";
        //  String crcString =  pagestatus.cmdArray[currentPosition];
        //  String nexts = "5aa5078200030000ac1e";
        // String crcString = cmdOne ;
        //   StringBuffer exCmd = CRC16.crc16(crcString);
        new Thread() {
            public void run() {
                super.run();
                try {
                    //   if (uartJint != null) {
                    boolean isSendx = false;
                   //  isSendx = uartJnit.getInstance().sendCmds(cmd);
                    // SetLoopData(ComA,cmd);
                    ComA.sendHex(cmd);
                    Log.e("send TAG", "send down: " + cmd);
                    Message msg = new Message();
                    if (isSendx) {
                        //  msg.what = 1;

                        Log.e("send TAG", "send down" + cmd + "success");
                    } else {
                        Log.e("TAG", "send down  :" + cmd + "failed!");
                    }
                    //    }
//
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    Thread.sleep((long) TIMER_INTERVAL);
                } catch (InterruptedException e2) {
                    e2.printStackTrace();

                }
            }


        }.start();
    }
    public void slidersend(int seekno,int sseq )
    {
        String cmdx = sPageJ.sliderCmd[seekno][sseq];
        // String tmpTmp = "C1200009";
        String cmdheader = "5AA50883";
        String feedheader = "5AA5";
        String allCmdx = cmdheader;
        String tmpTmp = cmdx;
        // allCmdx = allCmdx.concat(CRC16.expandStr(lcmd1Array[4]));
        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
        StringBuffer allCmd = CRC16.crc16x(allCmdx);
        final String cmd = allCmd.substring(0, 22);
        // String crcString = "83192001001F";
        //  String crcString =  pagestatus.cmdArray[currentPosition];
        //  String nexts = "5aa5078200030000ac1e";
        // String crcString = cmdOne ;
        //   StringBuffer exCmd = CRC16.crc16(crcString);
        new Thread() {
            public void run() {
                super.run();
                try {
                    //   if (uartJint != null) {
                    boolean isSendx = false;
                 //   isSendx = uartJnit.getInstance().sendCmds(cmd);
                    SetLoopData(ComA,cmd);
                    Log.e("send TAG", "send down: " + cmd);
                    Message msg = new Message();
                    if (isSendx) {
                        //  msg.what = 1;

                        Log.e("send TAG", "send down" + cmd + "success");
                    } else {
                        Log.e("TAG", "send down  :" + cmd + "failed!");
                    }
                    //    }
//
                } catch (Exception e) {
                    // e.printStackTrace();
                    return;
                }
                try {
                    Thread.sleep((long) TIMER_INTERVAL);
                } catch (InterruptedException e2) {
                    // e2.printStackTrace();
                    return;

                }
            }


        }.start();
    }
    //数值改变
    void  disinterwend(String device,String stat) {
        if (sPageJ.voladdress[6].equals(device)) {
            //  int fir = Integer.parseInt(stat.substring(2,3));
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2, 3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
            float lastx = (float) 0.0;
            lastx = (float) (value / 1.0);
            String  valuetext = "";
            NumberFormat formatter = new DecimalFormat("0.0");
            //  DecimalFormat df=new DecimalFormat("###.00");
            formatter.setRoundingMode(RoundingMode.HALF_UP);
            String formmatedFloatValue = formatter.format(lastx);
            if ((lastx > 15.0) && (lastx < 29.0)) {


                valuetext =formmatedFloatValue;
                if ((testwenView!= null)&&((sPageJ.pageno == 29)||(sPageJ.pageno == 229))) {
                    //   testwenView.setText( " " + valuetext + "°C" );
                    testwenView.setText( valuetext + "°C" );
                }

            } else {
                if((lastx <= 15.0) && (lastx > 0))
                {
                    if ((testwenView!= null)&&((sPageJ.pageno == 29)||(sPageJ.pageno == 229))) {
                        valuetext = "Lo";
                        // testwenView.setText("温度： " + valuetext  );
                        testwenView.setText(" " + valuetext  );
                    }

                }
                else if(lastx >= 29.0)
                {
                    if ((testwenView!= null)&&((sPageJ.pageno == 29)||(sPageJ.pageno == 229))) {
                        valuetext = "Hi";
                        //testwenView.setText("温度： " + valuetext   );
                        testwenView.setText(" " + valuetext   );
                        // testwenView.setText( "33 °C" );
                    }

                }

            }

        }
        // testwenView.setText( "33 °C" );
    }
    void  diswend(String device,String stat) {
        if (sPageJ.voladdress[2].equals(device)) {
            //  int fir = Integer.parseInt(stat.substring(2,3));
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2, 3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
            float lastx = (float) 0.0;
            lastx = (float) (value / 1.0);
            String  valuetext = "";
            NumberFormat formatter = new DecimalFormat("0.0");
          //  DecimalFormat df=new DecimalFormat("###.00");
            formatter.setRoundingMode(RoundingMode.HALF_UP);
            String formmatedFloatValue = formatter.format(lastx);
            if ((lastx > 15.0) && (lastx < 29.0)) {


                valuetext =formmatedFloatValue;
                if ((testwenView!= null)&&((sPageJ.pageno == 4)||(sPageJ.pageno == 204))) {
                 //   testwenView.setText( " " + valuetext + "°C" );
                    testwenView.setText( valuetext + "°C" );
                }

            } else {
                if((lastx <= 15.0) && (lastx > 0))
                {
                    if ((testwenView!= null)&&((sPageJ.pageno == 4)||(sPageJ.pageno == 204))) {
                        valuetext = "Lo";
                       // testwenView.setText("温度： " + valuetext  );
                        testwenView.setText(" " + valuetext  );
                    }

                }
                else if(lastx >= 29.0)
                {
                    if ((testwenView!= null)&&((sPageJ.pageno == 4)||(sPageJ.pageno == 204))) {
                        valuetext = "Hi";
                        //testwenView.setText("温度： " + valuetext   );
                        testwenView.setText(" " + valuetext   );
                       // testwenView.setText( "33 °C" );
                    }

                }

            }

        }
       // testwenView.setText( "33 °C" );
    }
    void  disfend(String device,String stat) {
        if (sPageJ.voladdress[3].equals(device)) {
            //  int fir = Integer.parseInt(stat.substring(2,3));
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2, 3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            // int value =   sec;
            int lastx = sec;
            // lastx = (int) (value / 10);
            //  NumberFormat formatter = new DecimalFormat("0.0");

            //String formmatedFloatValue = formatter.format(lastx);
            if ((lastx >=0) && (lastx <=7)) {


                if ((testfenView!= null)&&((sPageJ.pageno == 4)||(sPageJ.pageno == 204))) {
                    //  mania(pointValuea, lastx);
                   // if(lastx%1==0) {
                      //  testfenView.setText(lastx + "级");
                    testfenView.setText(lastx + "");
                  //  }
//                    else
//                    {
//                        testfenView.setText("0" + "级");
//                    }
                    //  testfenView.setText("风力： " + lastx+"级");
                }


            }
//            else
//            {
//                testfenView.setText("0" + "级");
//            }
        }
    }
    void  distestvend(String device,String stat) {
        //not finish .
        if (sPageJ.voladdress[5].equals(device)) {
            //  int fir = Integer.parseInt(stat.substring(2,3));
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2, 3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
           // int value =   sec;
            int lastx = sec;
           // lastx = (int) (value / 10);
          //  NumberFormat formatter = new DecimalFormat("0.0");

            //String formmatedFloatValue = formatter.format(lastx);
            if ((lastx >=1) && (lastx <=7)) {


                if ((testfenView!= null)&&((sPageJ.pageno == 4)||(sPageJ.pageno == 204))) {
                    //  mania(pointValuea, lastx);
                    if(lastx%1==0) {
                        testfenView.setText(lastx + "级");
                    }
                    else
                    {
                        testfenView.setText("0" + "级");
                    }
                  //  testfenView.setText("风力： " + lastx+"级");
                }


            }
//            else
//            {
//                testfenView.setText("0" + "级");
//            }
        }
    }


    public void createClock()
    {
//        iv_needle_time = (ImageView) findViewById(R.id.iv_needle_time); //速度ggg
//        iv_left_dot = (ImageView) findViewById(R.id.iv_left_dot);
//        iv_right_dot = (ImageView) findViewById(R.id.iv_right_dot);
        //iv_clock = (ImageView) findViewById(R.id.iv_clock);
       // iv_needle_hour = (ImageView) findViewById(R.id.iv_needle_hour);
     //   iv_needle_minute = (ImageView) findViewById(R.id.iv_needle_minute);
    //    iv_needle_second = (ImageView) findViewById(R.id.iv_needle_second);
      //  tv_date = (TextView) findViewById(R.id.tv_date);
//		iv_center = (ImageView) findViewById(R.id.iv_center);
//        tv_max = (TextView) findViewById(R.id.tv_max);
      //  ll_sb = (LinearLayout) findViewById(R.id.ll_sb);

        FrameLayout.LayoutParams paramclock=new FrameLayout.LayoutParams(convertWn(1024),convertHn(600));

        paramclock.leftMargin = convertWn(0)   ;
        paramclock.topMargin = convertHn(0)   ;

      // frame.addView( frameseond,paramclock);

        iv_needle_hour = new ImageView(this);
        Drawable kdhourdraw = getResources().getDrawable(R.drawable.kdhour);
        iv_needle_hour.setImageDrawable(kdhourdraw);

        FrameLayout.LayoutParams paramkdh=new FrameLayout.LayoutParams(convertWn(8),convertHn(134));

        paramkdh.leftMargin = convertWn(303)   ;
        paramkdh.topMargin = convertHn(246)   ;

        //    csImgView.setLayoutParams(paramsw);
         frame.addView(iv_needle_hour,paramkdh);



        iv_needle_minute = new ImageView(this);
        Drawable kdminitdraw = getResources().getDrawable(R.drawable.kdminute);
        iv_needle_minute.setImageDrawable(kdminitdraw);

        FrameLayout.LayoutParams paramkdm=new FrameLayout.LayoutParams(convertWn(6),convertHn(188));

        paramkdm.leftMargin = convertWn(304)   ;
        paramkdm.topMargin = convertHn(219)   ;

        //    csImgView.setLayoutParams(paramsw);
        frame.addView(iv_needle_minute,paramkdm);
        //
        iv_needle_second = new ImageView(this);
        Drawable kdseconddraw = getResources().getDrawable(R.drawable.kdsecond);
        iv_needle_second.setImageDrawable(kdseconddraw);

        FrameLayout.LayoutParams paramkds=new FrameLayout.LayoutParams(convertWn(4),convertHn(236));

        paramkds.leftMargin = convertWn(305)   ;
        paramkds.topMargin = convertHn(195)   ;

        //    csImgView.setLayoutParams(paramsw);
     //   frameseond.addView(iv_needle_second,paramkds);

//        iv_needle_hour.setRotation(45);
//        iv_needle_minute.setRotation(90);
//         iv_needle_second.setRotation(180);

        Calendar calendar=Calendar.getInstance();
        Date date =calendar.getTime();
        Long time=date.getTime();//年月日的毫秒值 日期比较大小时可以比较毫秒值
        SimpleDateFormat formatter = new SimpleDateFormat ("yyyy.MM.dd");
        String ymd=formatter.format(time);//yyyy-MM-dd
        //   tv_date.setText(ymd);

        Log.e("ymd = ",ymd);
        //  int year=calendar.get(Calendar.YEAR);//获取当前年
        //  int month=calendar.get(Calendar.MONTH)+1;//获取当前月 月份需要加1为当前月份
        //   int day=calendar.get(Calendar.DAY_OF_MONTH);//获取当前日
        inithourv=calendar.get(Calendar.HOUR);//获取当前日  HOUR_OF_DAY-24小时制
        initminutev=calendar.get(Calendar.MINUTE);//获取当前分
        initsecondv=calendar.get(Calendar.SECOND);//获取当前秒
        long initmill = calendar.get(Calendar.MILLISECOND);
        allsecond = initsecondv ;
        lastseconds = initsecondv;
        //  Log.e("ymd = ",ymd + inithourv + ":" + initminutev + ":" + initsecondv);
        //  dispt(hourv,minutev,secondv);
        //   disinito(inithourv,initminutev,initsecondv,initsecondv,initmill);
        disinit(inithourv,initminutev,initsecondv);

        float tmpst = initsecondv * 6f ;
        iv_needle_second.clearAnimation();
        //RotateAnimation tmp =
       rotate  = new RotateAnimation(tmpst, tmpst + 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        LinearInterpolator lin = new LinearInterpolator();
        rotate.setInterpolator(lin);
        rotate.setDuration(60000);//设置动画持续时间
        rotate.setRepeatCount(Animation.INFINITE);//设置重复次数
        rotate.setRepeatMode(Animation.RESTART);
        rotate.setFillAfter(false);//动画执行完后是否停留在执行完的状态
        rotate.setStartOffset(1000);//执行前的等待时间

     //   iv_needle_second
         iv_needle_second.setAnimation(rotate);

    }


    public void createRQ()
    {
        Button tmpBtn = new Button(this);
      //  tmpBtn.setBackgroundColor(Color.alpha(1));
        tmpBtn.setBackground(getDrawable(R.drawable.goback));
        //   FrameLayout.LayoutParams firstParams = new FrameLayout.LayoutParams(ConvertWn(120, 120);
        FrameLayout.LayoutParams firstParams = new FrameLayout.LayoutParams(convertWn(141), convertHn(30));

        firstParams.leftMargin = convertWn(29);
        firstParams.topMargin = convertHn(35);
        // firstParams.leftMargin = 80;
        //  firstParams.topMargin =  80;
        frame.addView(tmpBtn,firstParams);
        tmpBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                IntentIntegrator intentIntegrator = new IntentIntegrator(startActivity.this);
//                //tianjia  intentIntegrator.on
//                //   intentIntegrator.setCaptureActivity(CustomCaptureActivity.class);
//                // intentIntegrator.setTimeout(2000);
//                intentIntegrator.initiateScan();
                touchjmpback("");


            }
        });


    }
    public  void createWait()
    {
        rndImgView = new ImageView(this);
        Drawable rnddraw = getResources().getDrawable(R.drawable.kdround);
        rndImgView.setImageDrawable(rnddraw);



        FrameLayout.LayoutParams paramsrnd=new FrameLayout.LayoutParams(convertHn(14),convertHn(14));

        paramsrnd.leftMargin = convertWn(300)   ;
        paramsrnd.topMargin = convertHn(305)   ;

        //    csImgView.setLayoutParams(paramsw);
        frame.addView(rndImgView,paramsrnd);


        csImgView = new ImageView(this);
        Drawable csdraw = getResources().getDrawable(R.drawable.handle1);
        csImgView.setImageDrawable(csdraw);
        String tmpStat = sPageJ.feedMap.get(sPageJ.voladdress[4]);


        FrameLayout.LayoutParams paramstt=new FrameLayout.LayoutParams(convertWn(14),convertHn(112));

        paramstt.leftMargin = convertWn(300)   ;
        paramstt.topMargin = convertHn(207)   ;

    //    csImgView.setLayoutParams(paramsw);
      //  frame.addView(csImgView,paramstt);

        swdView = new TextView(this);

        swdView.setText("");


        Typeface typefacex= Typeface.createFromAsset(getAssets(),"yj.ttf");
        swdView.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);

        // testwenView.setTextColor(getResources().getColor(R.color.colorPrimary));

        swdView.setTextSize(22);
        swdView.setGravity(Gravity.CENTER);
      //  swdView.setGravity(Gravity.LEFT);
        //    testfView.setGravity(Gravity.RIGHT);

        // csView.setTextColor(0xffffffff);
        swdView.setTextColor(0xffffffff);
        //
        //  int mWidth = waittestwenView.getMeasuredWidth();
        //  int mHeight = waittestwenView.getMeasuredHeight();on


        FrameLayout.LayoutParams paramswd=new FrameLayout.LayoutParams(convertWn(974-757),convertHn(195-164));
        paramswd.leftMargin = convertWn(750+ sPageJ.offset29)   ;
        paramswd.topMargin = convertHn(164)   ;

       // swdView.setLayoutParams(paramswd);
        frame.addView(swdView,paramswd);

        csView = new TextView(this);

       csView.setText("");
        String tmpStatx = sPageJ.feedMap.get(sPageJ.voladdress[4]);
        if(!tmpStatx.equals("0000") && !tmpStatx.equals(""))
        {
            diswait(sPageJ.voladdress[4],tmpStatx);

        }

     //   Typeface typefacex= Typeface.createFromAsset(getAssets(),"yj.ttf");
       csView.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);

       // testwenView.setTextColor(getResources().getColor(R.color.colorPrimary));

        csView.setTextSize(50);
       // testwenView.setGravity(Gravity.LEFT);
        csView.setGravity(Gravity.CENTER);
        //    testfView.setGravity(Gravity.RIGHT);

       // csView.setTextColor(0xffffffff);
        csView.setTextColor(0xffffffff);
     //
      //  int mWidth = waittestwenView.getMeasuredWidth();
      //  int mHeight = waittestwenView.getMeasuredHeight();


        FrameLayout.LayoutParams paramcs=new FrameLayout.LayoutParams(convertWn(120),convertHn(80));
        paramcs.leftMargin = convertWn(248)   ;
        paramcs.topMargin = convertHn(335)   ;

       // csView.setLayoutParams(paramcs);
     //   frame.addView(csView,paramcs);

        avertView = new TextView(this);

        avertView.setText("");

        avertView.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);

        avertView.setTextSize(50);
        // testwenView.setGravity(Gravity.LEFT);
        avertView.setGravity(Gravity.CENTER);
        //    testfView.setGravity(Gravity.RIGHT);

        // csView.setTextColor(0xffffffff);
        avertView.setTextColor(0xffffffff);
        //
        //  int mWidth = waittestwenView.getMeasuredWidth();
        //  int mHeight = waittestwenView.getMeasuredHeight();


        FrameLayout.LayoutParams paramavert=new FrameLayout.LayoutParams(convertWn(100),convertHn(60));
        paramavert.leftMargin = convertWn(802+ sPageJ.offset29)   ;
        paramavert.topMargin = convertHn(91)   ;

       avertView.setLayoutParams(paramavert);
        frame.addView(avertView,paramavert);


        //    frame.addView(testfView);
       airqView = new TextView(this);
        // testView.setMargins(convertWn(566), convertHn(268), convertWn(936), convertHn(303));
        //  testView.setPadding(convertWn(187), convertHn(176), convertWn(422), convertHn(278));
        // testView.setPadding(187, 156, 422, 278);
        airqView.setText("air q");
        //  testView.setText("1" + "2.5");
       // testfenView.setGravity(Gravity.LEFT);
        airqView.setGravity(Gravity.CENTER);
        String ftmpStat = sPageJ.feedMap.get(sPageJ.voladdress[5]);
        if(!ftmpStat.equals("0000"))
        {
           diswait(sPageJ.voladdress[5],ftmpStat);
        }

        //   Typeface typeface= Typeface.createFromAsset(getAssets(),"yj.ttf");
       airqView.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);

       //16612464
       airqView.setTextColor(0xffffffff);
        // testView.setTextSize(232);
        // testView.setTextSize(convertHn(180));
        airqView.setTextSize(50);

       // tx.setTextColor(0xffff00f);

        //   LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        FrameLayout.LayoutParams paramsff=new FrameLayout.LayoutParams( convertWn(84),convertHn(64));

//        params.leftMargin = convertWn(187) + tWidth/2 ;
//        params.topMargin = convertHn(166) +  tHeight / 2;
        paramsff.leftMargin = convertWn(802+ sPageJ.offset29)  ;
        paramsff.topMargin = convertHn(409)  ;
        airqView.setLayoutParams(paramsff);
        // this.addContentView(testView,params);
        // testView.setText("12".concat(".5"));
        frame.addView(airqView,paramsff);
        //   MainActivityw.AsyncTaskRunner runner = new MainActivityw.AsyncTaskRunner();
        //String sleepTime = "10:0000000123456";
        //  runner.execute();

        airqImgView = new ImageView(this);
        Drawable airqdraw = getResources().getDrawable(R.drawable.bty1_off);
        airqImgView.setImageDrawable(airqdraw);



        FrameLayout.LayoutParams paramsairq=new FrameLayout.LayoutParams(convertWn(24),convertHn(24));

        paramsairq.leftMargin = convertWn(907+ sPageJ.offset29)   ;
        paramsairq.topMargin = convertHn(482)   ;

        //    csImgView.setLayoutParams(paramsw);
      //  frame.addView(airqImgView,paramsairq);
        initpView();
  //      startLocation();
        inittView();
        String sscode = sgetcode();
        String ssloc = sgetarea();
        if(locView != null)
        {
            locView.setText(ssloc);
            initweather(sPageJ.initacode);
        }

       // removeclock();
        createClock();
    }

    private  void removeclock()
    {

//        if(  iv_needle_hour != null) frame.removeView(iv_needle_hour);
//        if(  iv_needle_minute != null) frame.removeView(iv_needle_minute);
      if(  iv_needle_second != null) {

          frame.removeView(iv_needle_second);
          iv_needle_second.clearAnimation();
      }
          //frame.removeView(iv_needle_second);
//        iv_needle_second = null;
//        iv_needle_hour = null;
//        iv_needle_second = null;
    }
    public  void  inittView()
    {
        ttView = new TextView(this);

        ttView.setText("");

        Typeface typeface= Typeface.createFromAsset(getAssets(),"yj.ttf");
        ttView.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
  // * Typeface.DEFAULT //常规字体类型

    //        * Typeface.DEFAULT_BOLD //黑体字体类型
        // testwenView.setTextColor(getResources().getColor(R.color.colorPrimary));
        FrameLayout.LayoutParams paramtt=new FrameLayout.LayoutParams(convertWn(940-801),convertHn(314-255));

        paramtt.leftMargin = convertWn(783+ sPageJ.offset29)   ;
        paramtt.topMargin = convertHn(255)   ;

         ttView.setLayoutParams(paramtt);
        frame.addView(ttView,paramtt);
       ttView.setTextSize(50);
          ttView.setGravity(Gravity.LEFT);
      //  ttView.setGravity(Gravity.CENTER);
        //    testfView.setGravity(Gravity.RIGHT);

        // csView.setTextColor(0xffffffff);
        ttView.setTextColor(0xffffffff);

        //
        //  int mWidth = waittestwenView.getMeasuredWidth();
        //  int mHeight = waittestwenView.getMeasuredHeight();
        FrameLayout.LayoutParams paramtd=new FrameLayout.LayoutParams(convertWn(300),convertHn(345-307));

      //  paramtd.leftMargin = convertWn(598)   ;
        paramtd.leftMargin = convertWn(763+ sPageJ.offset29)   ;
        paramtd.topMargin = convertHn(341)   ;


       // ttView.setLayoutParams(paramtt);




        tdView = new TextView(this);

        tdView.setText("");

       // Typeface typeface= Typeface.createFromAsset(getAssets(),"yj.ttf");
        tdView.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
        // * Typeface.DEFAULT //常规字体类型

        //        * Typeface.DEFAULT_BOLD //黑体字体类型
        // testwenView.setTextColor(getResources().getColor(R.color.colorPrimary));

        tdView.setTextSize(22);
        tdView.setGravity(Gravity.LEFT);
        //tdView.setGravity(Gravity.CENTER);
        //    testfView.setGravity(Gravity.RIGHT);

        // csView.setTextColor(0xffffffff);
        tdView.setTextColor(0xffffffff);
        frame.addView(tdView,paramtd);
        settime();
        //   MainActivityw.AsyncTaskRunner runner = new MainActivityw.AsyncTaskRunner();
        //String sleepTime = "10:0000000123456";
        //  runner.execute();


        //初始化定位
        // initpLocation();
    }

   void settime()
    {
        Calendar calendar = Calendar.getInstance();
        Date date =calendar.getTime();
        Long timex=date.getTime();//年月日的毫秒值 日期比较大小时可以比较毫秒值
        SimpleDateFormat formatter = new SimpleDateFormat ("HH:mm");
        String ymdt=formatter.format(timex);//yyyy-MM-dd
        String ymd = "";
        try {
            ymd =  ThreadLocalDateUtil.formatDate(date);
        }
        catch(Exception e)
        {

        }

        ttView.setText(ymdt);
        tdView.setText(ymd);
    }
    private void initpLocation(){
        //初始化clientcreate
        locationClient = new AMapLocationClient(this.getApplicationContext());
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
    }

    /**
     * 默认的定位参数
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private AMapLocationClientOption getDefaultOption(){
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        mOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.DEFAULT);//可选，设置逆地理信息的语言，默认值为默认语言（根据所在地区选择语言）
        return mOption;
    }
    private  void initweather(final String  acode){

       final OkHttpClient client = new OkHttpClient();

        String url = "https://restapi.amap.com/v3/weather/weatherInfo?extensions=all&" + "key=dc34a5e8cffccf0f1f67c79b0c93976e&city=" + acode;
        Request request = new Request.Builder().get()
                .url(url)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
                         @Override
                         public void onFailure(@NotNull Call call, @NotNull IOException e) {

                         }

                         @Override
                         public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                             JSONObject todayJson = null;
                             try {
                                 String jsonString = response.body().string();
                                 //把访问url得到的数据打印出来
                                 JSONObject json = JSONObject.parseObject(jsonString);
                                 JSONArray castsJson = json.getJSONArray("forecasts");
                                 todayJson = castsJson.getJSONObject(0).getJSONArray("casts").getJSONObject(0);
                             } catch (Exception e) {

                             }
                             if (todayJson == null) {
                                 return;
                             }
                             final int nighttemp = todayJson.getIntValue("nighttemp");
                             final int daytemp = todayJson.getIntValue("daytemp");
                             startActivity.this.runOnUiThread(new Runnable() {
                                 @Override
                                 public void run() {
//                        maxtemp.setText(daytemp + "℃");
//                        mintemp.setText(nighttemp + "℃");
                                 }
                             });
                             String realtimeurl = "https://restapi.amap.com/v3/weather/weatherInfo?&" + "key=dc34a5e8cffccf0f1f67c79b0c93976e&city=" + acode;
                             Request realtimequest = new Request.Builder().get()
                                     .url(realtimeurl)
                                     .build();
                             Call todycall = client.newCall(realtimequest);
                             todycall.enqueue(new Callback() {
                                 @Override
                                 public void onFailure(Call call, IOException e) {

                                 }

                                 @Override
                                 public void onResponse(Call call, Response response) throws IOException {
                                     //一般会得到Json数据，这时候就要用Json解析的一系列方法处理了，网上都可查这里不多讲
                                     String jsonString = response.body().string();
                                     //把访问url得到的数据打印出来
                                     JSONObject json = JSONObject.parseObject(jsonString);
                                     JSONArray livejson = json.getJSONArray("lives");
                                     if (livejson == null) {
                                         return;
                                     }
                                     final String weather = livejson.getJSONObject(0).getString("weather");
                                     Log.e("weather = ", weather);


                                         // sb.append("定位成功" + "\n");
//                    sb.append("定位类型: " + location.getLocationType() + "\n");
//                    sb.append("经    度    : " + location.getLongitude() + "\n");
//                    sb.append("纬    度    : " + location.getLatitude() + "\n");
                                     //String alltq = "" + nighttemp + daytemp + "°" + "" + weather;
                                   final  int temperature = livejson.getJSONObject(0).getIntValue("temperature");
                                     startActivity.this.runOnUiThread(new Runnable() {
                                         public void run() {
                                             StringBuffer sbx = new StringBuffer();
                                             sbx.append( nighttemp);
                                             sbx.append(" /" + daytemp);
                                             sbx.append("°    ");
                                             sbx.append(weather);
                                             String alltq = sbx.toString();
                                            // testbtnFeed(currentPositionww,false);
                                             swdView.setText(alltq);

                                           //  Log.e("temprature = ", temperature + "");
                                             avertView.setText(temperature + "°C ");
                                         }
                                     });


                                     startActivity.this.runOnUiThread(new Runnable() {
                                         @Override
                                         public void run() {
                                             //  int value = (int) (((float) temperature - nighttemp) / (daytemp - nighttemp) * 100);
                                             //  bar2.setProgress(value);
                                             if (weather.contains("晴")) {
                                                 weatherImg.setImageResource(R.mipmap.p21);
                                             }
                                             if (weather.contains("阴")) {
                                                 weatherImg.setImageResource(R.mipmap.p20);
                                             }
                                             if (weather.contains("多云转晴")) {
                                                 weatherImg.setImageResource(R.mipmap.p19);
                                             }
                                             if (weather.contains("雷雨")) {
                                                 weatherImg.setImageResource(R.mipmap.p18);
                                             }
                                             if (weather.contains("浮尘")) {
                                                 weatherImg.setImageResource(R.mipmap.p25);
                                             }
                                             if (weather.contains("沙尘暴")) {
                                                 weatherImg.setImageResource(R.mipmap.p17);
                                             }
                                             if (weather.contains("霾")) {
                                                 weatherImg.setImageResource(R.mipmap.p16);
                                             }
                                             if (weather.contains("雾")) {
                                                 weatherImg.setImageResource(R.mipmap.p16);
                                             }
                                             if (weather.contains("多云")) {
                                                 weatherImg.setImageResource(R.mipmap.p15);
                                             }

                                             if (weather.contains("中雨转晴")) {
                                                 weatherImg.setImageResource(R.mipmap.p14);
                                             }
                                             if (weather.contains("雷雨转晴")) {
                                                 weatherImg.setImageResource(R.mipmap.p13);
                                             }
                                             if (weather.contains("中雨")) {
                                                 weatherImg.setImageResource(R.mipmap.p12);
                                             }
                                             if (weather.contains("大雨")) {
                                                 weatherImg.setImageResource(R.mipmap.p12);
                                             }
                                             if (weather.contains("中雪")) {
                                                 weatherImg.setImageResource(R.mipmap.p10);
                                             }
                                             if (weather.contains("小雪转中雪")) {
                                                 weatherImg.setImageResource(R.mipmap.p9);
                                             }
                                             if (weather.contains("雨夹雪")) {
                                                 weatherImg.setImageResource(R.mipmap.p8);
                                             }
                                             if (weather.contains("冰雹")) {
                                                 weatherImg.setImageResource(R.mipmap.p7);
                                             }
                                             if (weather.equals("雨加冰雹")) {

                                                 weatherImg.setImageResource(R.mipmap.p6);
                                             }
                                             if (weather.contains("大雪")) {

                                                 weatherImg.setImageResource(R.mipmap.p5);

                                             }

                                         }
                                     });
                                 }

                             });

                         }
                     });
    }
    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {

                StringBuffer sb = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if(location.getErrorCode() == 0) {
//                    addresscode =  location.getAdCode();
//                    if(!addresscode.equals("")) {
//                        initweather(addresscode);
//                    }
                    // sb.append("定位成功" + "\n");
//                    sb.append("定位类型: " + location.getLocationType() + "\n");
//                    sb.append("经    度    : " + location.getLongitude() + "\n");
//                    sb.append("纬    度    : " + location.getLatitude() + "\n");
//                    sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
//                    sb.append("提供者    : " + location.getProvider() + "\n");
//
//                    sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
//                    sb.append("角    度    : " + location.getBearing() + "\n");
                    // 获取当前提供定位服务的卫星个数
//                    sb.append("星    数    : " + location.getSatellites() + "\n");
//                    sb.append("国    家    : " + location.getCountry() + "\n");
//                    sb.append("省            : " + location.getProvince() + "\n");
                    sb.append(location.getCity());
//                    sb.append("城市编码 : " + location.getCityCode() + "\n");
                    sb.append(location.getDistrict() + "");
                }
//                    sb.append("区域 码   : " + location.getAdCode() + "\n");
//                    sb.append("地    址    : " + location.getAddress() + "\n");
//                    sb.append("兴趣点    : " + location.getPoiName() + "\n");
//                    //定位完成的时间
//                    sb.append("定位时间: " + mapUtils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
//                } else {
//                    //定位失败
//                    sb.append("定位失败" + "\n");
//                    sb.append("错误码:" + location.getErrorCode() + "\n");
//                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
//                    sb.append("错误描述:" + location.getLocationDetail() + "\n");
//                }
//                sb.append("***定位质量报告***").append("\n");
//                sb.append("* WIFI开关：").append(location.getLocationQualityReport().isWifiAble() ? "开启":"关闭").append("\n");
//                sb.append("* GPS状态：").append(getGPSStatusString(location.getLocationQualityReport().getGPSStatus())).append("\n");
//                sb.append("* GPS星数：").append(location.getLocationQualityReport().getGPSSatellites()).append("\n");
//                sb.append("* 网络类型：" + location.getLocationQualityReport().getNetworkType()).append("\n");
//                sb.append("* 网络耗时：" + location.getLocationQualityReport().getNetUseTime()).append("\n");
//                sb.append("****************").append("\n");
//                //定位之后的回调时间
//                sb.append("回调时间: " + mapUtils.formatUTC(System.currentTimeMillis(), "yyyy-MM-dd HH:mm:ss") + "\n");

                //解析定位结果，
                String result = sb.toString();
                locView.setText(result);


                addresscode =  location.getAdCode();
                if(!addresscode.equals("")) {
                    ssetMyip(addresscode,result);
                    initweather(addresscode);
                }

            } else {
              locView.setText("定位失败");
            }
        }
    };


    /**
     * 获取GPS状态的字符串
     * @param statusCode GPS状态码
     * @return
     */
    private String getGPSStatusString(int statusCode){
        String str = "";
        switch (statusCode){
            case AMapLocationQualityReport.GPS_STATUS_OK:
                str = "GPS状态正常";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPROVIDER:
                str = "手机中没有GPS Provider，无法进行GPS定位";
                break;
            case AMapLocationQualityReport.GPS_STATUS_OFF:
                str = "GPS关闭，建议开启GPS，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_MODE_SAVING:
                str = "选择的定位模式中不包含GPS定位，建议选择包含GPS定位的模式，提高定位质量";
                break;
            case AMapLocationQualityReport.GPS_STATUS_NOGPSPERMISSION:
                str = "没有GPS定位权限，建议开启gps定位权限";
                break;
        }
        return str;
    }
    // 根据控件的选择，重新设置定位参数
    private void resetOption() {
        // 设置是否需要显示地址信息
//        locationOption.setNeedAddress(cbAddress.isChecked());
//        /**
//         * 设置是否优先返回GPS定位结果，如果30秒内GPS没有返回定位结果则进行网络定位
//         * 注意：只有在高精度模式下的单次定位有效，其他方式无效
//         */
//        locationOption.setGpsFirst(cbGpsFirst.isChecked());
//        // 设置是否开启缓存
//        locationOption.setLocationCacheEnable(cbCacheAble.isChecked());
//        // 设置是否单次定位
//        locationOption.setOnceLocation(cbOnceLocation.isChecked());
//        //设置是否等待设备wifi刷新，如果设置为true,会自动变为单次定位，持续定位时不要使用
//        locationOption.setOnceLocationLatest(cbOnceLastest.isChecked());
//        //设置是否使用传感器
//        locationOption.setSensorEnable(cbSensorAble.isChecked());
//        //设置是否开启wifi扫描，如果设置为false时同时会停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
//        String strInterval = etInterval.getText().toString();
        locationOption.setNeedAddress(true);
        /**
         * 设置是否优先返回GPS定位结果，如果30秒内GPS没有返回定位结果则进行网络定位
         * 注意：只有在高精度模式下的单次定位有效，其他方式无效
         */
        locationOption.setGpsFirst(true);
        // 设置是否开启缓存
        locationOption.setLocationCacheEnable(true);
        // 设置是否单次定位
        locationOption.setOnceLocation(true);
        //设置是否等待设备wifi刷新，如果设置为true,会自动变为单次定位，持续定位时不要使用
        locationOption.setOnceLocationLatest(true);
        //设置是否使用传感器
        locationOption.setSensorEnable(true);
        //设置是否开启wifi扫描，如果设置为false时同时会停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        String strInterval = "1000";
        if (!TextUtils.isEmpty(strInterval)) {
            try{
                // 设置发送定位请求的时间间隔,最小值为1000，如果小于1000，按照1000算
                locationOption.setInterval(Long.valueOf(strInterval));
            }catch(Throwable e){
                e.printStackTrace();
            }
        }

        String strTimeout = "5000";
        if(!TextUtils.isEmpty(strTimeout)){
            try{
                // 设置网络请求超时时间
                locationOption.setHttpTimeOut(Long.valueOf(strTimeout));
            }catch(Throwable e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 开始定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void startLocation(){
        //根据控件的选择，重新设置定位参数
        resetOption();
        // 设置定位参数
        locationClient.setLocationOption(locationOption);
        // 启动定位
        locationClient.startLocation();
    }

    /**
     * 停止定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void stopLocation(){
        // 停止定位
        locationClient.stopLocation();
    }

    /**
     * 销毁定位
     *
     * @since 2.8.0
     * @author hongming.wang
     *
     */
    private void destroyLocation(){
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }
    public  void  initpView()
    {
        weatherImg = new ImageView(this);
        FrameLayout.LayoutParams paramwe=new FrameLayout.LayoutParams(convertWn(935-883),convertHn(155-117));

        paramwe.leftMargin = convertWn(883+sPageJ.offset29)   ;
        paramwe.topMargin = convertHn(117)   ;
       // weatherImg.setImageResource(R.mipmap.ic_launcher_round);
        weatherImg.setLayoutParams(paramwe);
        frame.addView(weatherImg,paramwe);


        locView = new TextView(this);
        locView.setText("定位中...");
        //locView.setText("天津市滨海新区");
       // locView.setText("新疆维吾尔自治区");
        Typeface typeface= Typeface.createFromAsset(getAssets(),"yj.ttf");
        locView.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
        locView.setTextSize(22);
        locView.setGravity(Gravity.LEFT);
        locView.setTextColor(0xffffffff);
        FrameLayout.LayoutParams paramsw=new FrameLayout.LayoutParams(convertWn(243),convertHn(38));
        paramsw.leftMargin = convertWn(783+sPageJ.offset29)   ;
        paramsw.topMargin = convertHn(211)   ;
        //locView.setLayoutParams(paramsw);
        frame.addView(locView,paramsw);


        airlocView = new TextView(this);
        airlocView.setText("空气质量");

        airlocView.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
        airlocView.setTextSize(22);
       // airlocView.setGravity(Gravity.CENTER);
        airlocView.setGravity(Gravity.LEFT);
        airlocView.setTextColor(0xffffffff);
        FrameLayout.LayoutParams paramairloc=new FrameLayout.LayoutParams(convertWn(243),convertHn(38));
        paramairloc.leftMargin = convertWn(783+sPageJ.offset29)   ;
        paramairloc.topMargin = convertHn(477)   ;
       // airlocView.setLayoutParams(paramairloc);
        frame.addView(airlocView,paramairloc);

        //   MainActivityw.AsyncTaskRunner runner = new MainActivityw.AsyncTaskRunner();
        //String sleepTime = "10:0000000123456";
        //  runner.execute();


        //初始化定位
       // initpLocation();
    }


    public  void createWF()
    {
        testwenView = new TextView(this);

        testwenView.setText("");
        String tmpStat = sPageJ.feedMap.get(sPageJ.allDArray[60]);
        if(!tmpStat.equals("0000") && !tmpStat.equals(""))
        {
            diswend(sPageJ.allDArray[60],tmpStat);

        }

        Typeface typeface= Typeface.createFromAsset(getAssets(),"yj.ttf");
      // testwenView.setTypeface(typeface);//第一句话“离离原上草，一岁一枯荣”引入lanti.ttf字体库
    testwenView.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
        // testwenView.setTextColor(getResources().getColor(R.color.colorPrimary));

        testwenView.setTextSize(32);
        // testwenView.setGravity(Gravity.LEFT);
        testwenView.setGravity(Gravity.CENTER);
        //    testfView.setGravity(Gravity.RIGHT);

        testwenView.setTextColor(0xffffffff);
        //
        int mWidth = testwenView.getMeasuredWidth();
        int mHeight = testwenView.getMeasuredHeight();

        FrameLayout.LayoutParams paramsw=new FrameLayout.LayoutParams(convertWn(88),convertHn(36));

        paramsw.leftMargin = convertWn(445)   ;
        paramsw.topMargin = convertHn(192)   ;

        testwenView.setLayoutParams(paramsw);
        frame.addView(testwenView,paramsw);
        //    frame.addView(testfView);
        testfenView = new TextView(this);
        // testView.setMargins(convertWn(566), convertHn(268), convertWn(936), convertHn(303));
        //  testView.setPadding(convertWn(187), convertHn(176), convertWn(422), convertHn(278));
        // testView.setPadding(187, 156, 422, 278);
        testfenView.setText("");
        //  testView.setText("1" + "2.5");
        // testfenView.setGravity(Gravity.LEFT);
        testfenView.setGravity(Gravity.CENTER);
        String ftmpStat = sPageJ.feedMap.get(sPageJ.allDArray[61]);
        if(!ftmpStat.equals("0000"))
        {
            disfend(sPageJ.allDArray[61],ftmpStat);
        }

        //   Typeface typeface= Typeface.createFromAsset(getAssets(),"yj.ttf");
      //  testfenView.setTypeface(typeface);
        testfenView.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
        //16612464
        testfenView.setTextColor(0xffffffff);
        // testView.setTextSize(232);
        // testView.setTextSize(convertHn(180));
        testfenView.setTextSize(32);

        // tx.setTextColor(0xffff00f);

        //   LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        FrameLayout.LayoutParams paramsff=new FrameLayout.LayoutParams( convertWn(48),convertHn(36));

//        params.leftMargin = convertWn(187) + tWidth/2 ;
//        params.topMargin = convertHn(166) +  tHeight / 2;
        paramsff.leftMargin = convertWn(587)  ;
        paramsff.topMargin = convertHn(192)  ;
        testfenView.setLayoutParams(paramsff);
        // this.addContentView(testView,params);
        // testView.setText("12".concat(".5"));
        frame.addView(testfenView,paramsff);
        //   MainActivityw.AsyncTaskRunner runner = new MainActivityw.AsyncTaskRunner();
        //String sleepTime = "10:0000000123456";
        //  runner.execute();

    }

    public static void forwardM(String mess)

    {  if(mess.indexOf("f003")!=-1) {
        Log.e("forwardx", mess + "\n");
    }

        if(serverThread!=null) {
            if(!clientdos.isEmpty())
            {
                 if(!lastV.equals(mess)) {
                for (Map.Entry<String, OutputStream> entry : clientdos.entrySet()) {
                    //  for (OutputStream dos : clientdos.values()) {
                    try {

                        OutputStream dos = entry.getValue();

                        // mess = mess + "0D0A";

                        //    serverThread.dos.write(TransformUtils.hexStringToBytes(mess));
                        if(mess.indexOf("f003")!=-1) {
                            Log.e("forwardeee", mess + "\n");
                        }
                        // serverThread.dos.write(mess.getBytes());
                        dos.write(TransformUtils.hexStringToBytesxx(mess));
                        // PrintWriter pw=new PrintWriter(serverThread.dos);
                        //  pw.write(mess);

                        //  pw.flush();
                        lastV = mess;

                        //  serverThread.dos.write(mess);
                        dos.flush();


                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            }
        }
        else
        {
            ////  synchronized  {
            clientMap = null;
            clientdis = null;
            clientdos = null;
            //}
        }

//        try {
//            LocalSocket sender = new LocalSocket();
//
////建立对应地址连接
//            sender.connect(new LocalSocketAddress(SOCKET_ADDRESS));
//
////发送写入数据
//            sender.getOutputStream().write(mess.getBytes());
//            sender.getOutputStream().close();
//        }
//        catch(Exception ex)
//        {
//
//        }

//关闭socket

    }

    public  String  revertValue (int value)
    {
        int fir = value/16;
        int sec = value%16;
        String res = "00";
        StringBuffer sb = new StringBuffer(res);
        sb.append(CRC16.convertF(fir));
        sb.append(CRC16.convertF(sec));
        return  sb.toString();
        //int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
        //int sec = Integer.parseInt(stat.substring(3));
        // int value = fir * 16 + sec;

    }

//    public  void createSeek32()
//    {
//        // seekBar2 = new VerticalSeekBar_Reverse(this);
//        seekBar2 = new nSeekBar(this);
//        // seekBar2 = new SeekBar(this);
//
//        // seekBar2.setTag(2);
//      //  Drawable draw = getResources().getDrawable(R.drawable.e10);
//       //  seekBar2.setProgressDrawable(draw);
//        seekBar2.setProgressDrawable(getDrawable(R.drawable.prog_image32));
//
//         //  seekBar2.setThumb(getDrawable(R.drawable.d11));
//       // seekBar2.setThumb(getDrawable(R.drawable.e11));
//        seekBar2.setThumb(getDrawable(R.drawable.thumb_image32));
//        seekBar2.setMinimumHeight(convertHn(0));
//
//        FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(convertWn(290), convertHn(24));
//
//        headParams.leftMargin = convertWn(284);
//        headParams.topMargin = convertHn(415);
//        // headParams.topMargin = convertHn(108);
//
//        seekBar2.setLayoutParams(headParams);
//
//        seekBar2.setPadding(0, 0, 0, 0);
//
//        seekBar2.setSplitTrack(false);
//        seekBar2.setThumbOffset(convertWn(0));
//        //      frame.addView(testView);
//        frame.addView(seekBar2);
//        // seekBar.setPadding(500,100, 50,700);
//        seekBar2.bringToFront();
//        // seekBar2.setOnSeekBarChangeListener(this);
//
//        //seekBar.setMin(1);
//
//        seekBar2.setMax (100);
//        // seekBar2.setKeyProgressIncrement(10);
//        seekBar2.setKeyProgressIncrement(1);
//        seekBar2.setTag(2);
//
////        for (int hh=2;hh<3;hh++) {
////            String tmpStat = sPageJ.feedMap.get(sPageJ.allDArray[hh+10]);
////            if (!tmpStat.equals("0000")) {
////                dish(sPageJ.allDArray[hh+10], tmpStat);
////            }
////        }
//
//        String tmpStat = sPageJ.feedMap.get(sPageJ.allDArray[23]);
//
//        disvol(sPageJ.allDArray[23], tmpStat);
//
//
////        SeekBar.OnSeekBarChangeListener onseek = new SeekBar.OnSeekBarChangeListener() {
////            @Override
////            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
////
////                int type = 0;
////                int tmp = (int) seekBar.getTag();
////                 int firpara = progress  ;
////
////               // int firpara = progress / 10 ;
//////        if (feedOK(feedDevice[cc])) {
//////            sPageJ.feedMap.put(feedDevice[cc], feedStatus[cc]);
//////        }
////               // String myvalue = revertValue(firpara * 10);
////                if (feedOK(sPageJ.allDArray[10+tmp])) {
////                   // sPageJ.feedMap.put(sPageJ.allDArray[10+tmp], revertValue(firpara * 10));
////                    sPageJ.feedMap.put(sPageJ.allDArray[10+tmp], revertValue(firpara));
////                }
////
////
////                //  testView.setText("当前数值："+ firpara);
////                if((firpara < 100)&&(firpara!=lfirseekvt)) {
////                    //   String cmdx = sPageJ.sliderCmd[tmp][firpara];
////                  //  String cmdx = sPageJ.sliderCmd[tmp][firpara];
////
////                    String cmdx = getNextCmd(tmp,firpara);
////                    // if (progress % 10 == 0) {
////                    //          testtView.setText("当前数值：" + cmdx);
////
////                    try {
////                        pslidersend(cmdx);
////
////                           // slidersend(tmp, firpara);
////                            lfirseekvt = firpara;
////
////                    }
////                    catch(Exception ex)
////                    {
////                        return;
////                    }
////                    //          }
////                }
////
////            }
////
////            @Override
////            public void onStartTrackingTouch(SeekBar seekBar) {
////
////            }
////
////            @Override
////            public void onStopTrackingTouch(SeekBar seekBar) {
////
////            }
////        };
//
//        seekBar2.setOnSeekBarChangeListener(onseek2);
//
//    }

//    public  void createSeek31x()
//    {
//
//        seekBar1 = new nSeekBar(this);
//        //  seekBar1 = new VerticalSeekBar(this);
//
//        Drawable draw = getResources().getDrawable(R.drawable.e5);
//        seekBar1.setProgressDrawable(getDrawable(R.drawable.prog_image31a));
//
//        //  seekBar2.setThumb(getDrawable(R.drawable.d11));
//        // seekBar2.setThumb(getDrawable(R.drawable.e11));
//        seekBar1.setThumb(getDrawable(R.drawable.thumb_image31a));
//
//      // seekBar1.setProgressDrawable(getDrawable(R.drawable.thumb_image31));
//       // seekBar1.setProgressDrawable(draw);
//
//        //  seekBar1.setThumb(getDrawable(R.drawable.thumb_image31));
//      //  seekBar1.setThumb(getDrawable(R.drawable.e6));
//
//        seekBar1.setMinimumHeight(convertHn(0));
//
//        //FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(convertWn(247), convertHn(25));
//        FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(convertWn(290), convertHn(24));
//
//        headParams.leftMargin = convertWn(284);
//        //  headParams.topMargin = convertHn(136);
//        headParams.topMargin = convertHn(226);
//
//        seekBar1.setLayoutParams(headParams);
//
//        //  seekBar1.setPadding(convertWn(0), convertHn(7), convertWn(0), convertHn(7));
//
//        seekBar1.setPadding(convertWn(0), 0, 0, 0);
//        seekBar1.setSplitTrack(false);
//        seekBar1.setThumbOffset(convertWn(0));
//        //      frame.addView(testView);
//        frame.addView(seekBar1);
//        // seekBar.setPadding(500,100, 50,700);
//        seekBar1.bringToFront();
//        seekBar1.setMax (100);
//        seekBar1.setKeyProgressIncrement(1);
//
//        seekBar1.setTag(1);
//        //  seekBar1.setOnSeekBarChangeListener(this);
//
//        seekBar1.setOnSeekBarChangeListener(onseek1);
////************
////        for (int hh=1;hh<2;hh++) {
////
////            String tmpStat = sPageJ.feedMap.get(sPageJ.allDArray[hh+10]);
////            if (!tmpStat.equals("0000")) {
////                dish(sPageJ.allDArray[hh+10], tmpStat);
////            }
////       }
//        String tmpStat = sPageJ.feedMap.get(sPageJ.allDArray[22]);
//        // if (!tmpStat.equals("0000")) {
//        disvol(sPageJ.allDArray[22], tmpStat);
//        // }
//
//    }

//    public  void createSeek31()
//    {
//        seekBar1 = new nSeekBar(this);
//        //  seekBar1 = new VerticalSeekBar(this);
//
//        Drawable draw1 = getResources().getDrawable(R.drawable.b7);
//
//      //  draw1.setBounds(convertWn(298),convertHn(528),convertWn(426), convertHn(64));
//      //  seekBar1.setProgressDrawable(draw1);
//      //  Drawable draw1 = getResources().getDrawable(R.drawable.prog_image31);
//      seekBar1.setProgressDrawable(getDrawable(R.drawable.prog_image31));
//
//
//      // seekBar1.setProgressDrawable(getDrawable(R.drawable.b7));
//         seekBar1.setThumb(getDrawable(R.drawable.thumb_image31));
//      //  Drawable draw2 = getDrawable(R.drawable.b8);
//      //  draw2.setBounds(convertWn(298),convertHn(336),convertWn(48), convertHn(48));
//       // seekBar1.setThumb(draw2);
//       // seekBar1.setThumb(getDrawable(R.drawable.b8));
//
//        seekBar1.setMinimumHeight(convertHn(0));
//
//        //FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(convertWn(247), convertHn(25));
//      //  FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(411, 49);
//        FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(convertWn(426), convertHn(64));
//
//       // headParams.leftMargin = convertWn(292);
//      //  headParams.topMargin = convertWn(536);
//         headParams.leftMargin = convertWn(298);
//          headParams.topMargin = convertHn(528);
//       // headParams.leftMargin = convertWn(305); 291 523
//        //  headParams.topMargin = convertHn(136);
//        //headParams.topMargin = convertHn(536);
//
//       // seekBar1.setLayoutParams(headParams);
//        frame.addView(seekBar1,headParams);
//
//        //  seekBar1.setPadding(convertWn(0), convertHn(7), convertWn(0), convertHn(7));
//
//        seekBar1.setPadding(convertWn(0), 0, 0, 0);
//        seekBar1.setSplitTrack(false);
//        seekBar1.setThumbOffset(convertWn(0));
//        //      frame.addView(testView);
//
//        // seekBar.setPadding(500,100, 50,700);
//        seekBar1.bringToFront();
//        seekBar1.setMax (100);
//        seekBar1.setKeyProgressIncrement(1);
//
//        seekBar1.setTag(1);
//        //  seekBar1.setOnSeekBarChangeListener(this);
//
//        seekBar1.setOnSeekBarChangeListener(onseek1);
////************
////        for (int hh=1;hh<2;hh++) {
////
////            String tmpStat = sPageJfeedMap.get(sPageJallDArray[hh+10]);
////            if (!tmpStat.equals("0000")) {
////                dish(sPageJallDArray[hh+10], tmpStat);
////            }
////       }
//        String tmpStat = sPageJ.feedMap.get(sPageJ.allDArray[22]);
//         if (!tmpStat.equals("0000")) {
//        disvol(sPageJ.allDArray[22], tmpStat);
//         }
//
//    }





    public  boolean feedOK(String entr)
    {
        boolean feedx = false;
        // new String[]{"0071", "0072", "0073", "0074","0075","0076","0081", "0082", "0083", "0084","0085","0086","0087","1010","1011","1012","1013","1014"};
        // String[] tmpAll = new String[]{"0071", "0072", "0073", "0074","0075","0076","0081", "0082", "0099", "0099","0099","0086","0087","1010","1011","71b0","72b0","73b0"};
        //  String[] tmpAll = new String[]{"d001", "f002", "d002", "f003","c001","c002","c003","c004","f00d", "f006", "f004","b009","b00a","1010","1011","71b0","72b0","73b0"};
        return  TransformUtils.isAvail(sPageJ.tmpAlla,entr);
    }

    SeekBar.OnSeekBarChangeListener onseek1 = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            int type = 0;
            int tmp = (int) seekBar.getTag();
            int firpara = progress  ;

            // int firpara = progress / 10 ;
//        if (feedOK(feedDevice[cc])) {
//            sPageJfeedMap.put(feedDevice[cc], feedStatus[cc]);
//        }
            // String myvalue = revertValue(firpara * 10);
//            if (feedOK(sPageJallDArray[10+tmp])) {
//                // sPageJfeedMap.put(sPageJallDArray[10+tmp], revertValue(firpara * 10));
//                sPageJfeedMap.put(sPageJallDArray[10+tmp], revertValue(firpara));
//            }
            if (feedOK(sPageJ.allDArray[22])) {
                // sPageJfeedMap.put(sPageJallDArray[10+tmp], revertValue(firpara * 10));
                sPageJ.feedMap.put(sPageJ.allDArray[22], revertValue(firpara));
            }


            //  testView.setText("当前数值："+ firpara);
            if((firpara < 101)&&(firpara!=lfirseekvt1)) {
                //   String cmdx = sPageJsliderCmd[tmp][firpara];
                //  String cmdx = sPageJsliderCmd[tmp][firpara];

                String cmdx = getNextCmd(tmp,firpara);
                // if (progress % 10 == 0) {
                //          testtView.setText("当前数值：" + cmdx);

                try {


                    if (fromUser ||(!isseek1feed)){
                        pslidersend(cmdx);
                    }

                    isseek1feed = false;
                    // slidersend(tmp, firpara);
                    lfirseekvt1 = firpara;
                    // }
                    //  }

                }
                catch(Exception ex)
                {
                    return;
                }
                //          }
            }

        }




        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    };

    SeekBar.OnSeekBarChangeListener onseek2 = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            int type = 0;
            int tmp = (int) seekBar.getTag();
            int firpara = progress  ;
            // VerticalSeekBar_Reverse vseekBar = (VerticalSeekBar_Reverse)seekBar;
            // boolean spp = vseekBar.specialTint;

            // int firpara = progress / 10 ;
//        if (feedOK(feedDevice[cc])) {
//            sPageJ.feedMap.put(feedDevice[cc], feedStatus[cc]);
//        }
            // String myvalue = revertValue(firpara * 10);
//            if (feedOK(sPageJ.allDArray[10+tmp])) {
//                // sPageJ.feedMap.put(sPageJ.allDArray[10+tmp], revertValue(firpara * 10));
//                sPageJ.feedMap.put(sPageJ.allDArray[10+tmp], revertValue(firpara));
//            }

            if (feedOK(sPageJ.allDArray[23])) {
                // sPageJ.feedMap.put(sPageJ.allDArray[10+tmp], revertValue(firpara * 10));
                sPageJ.feedMap.put(sPageJ.allDArray[23], revertValue(firpara));
            }

            //  testView.setText("当前数值："+ firpara);
            if((firpara < 101)&&(firpara!=lfirseekvt2)) {
                // if(firpara < 101) {
                //   String cmdx = sPageJ.sliderCmd[tmp][firpara];
                //  String cmdx = sPageJ.sliderCmd[tmp][firpara];

                String cmdx = getNextCmd(tmp,firpara);
                // if (progress % 10 == 0) {
                //          testtView.setText("当前数值：" + cmdx);

                try {

                    // if(fromUser) {
                    if (fromUser ||(!isseek2feed)){
                        // if ( spp||(!isseek2feed)) {
                        pslidersend(cmdx);

                    }
                    isseek2feed = false;

                    // slidersend(tmp, firpara);
                    lfirseekvt2 = firpara;
                    // }
                    //  }

                }
                catch(Exception ex)
                {
                    return;
                }
                //          }
            }

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    };

    void  disktv(String device,String stat) //空调 风力计算
    {
        if(sPageJ.voladdress[0].equals(device)){
            //  int fir = Integer.parseInt(stat.substring(2,3));
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
            float lastx = (float) 0.0;
            lastx = (float)(value/10.0);
            NumberFormat formatter = new DecimalFormat("00.0");

            String formmatedFloatValue = formatter.format(lastx);
            if((lastx > 9.9) && (lastx < 14.6)) {
//                if(testView == null) {
//
//                }
//                else {
//
//                    if(sPageJ.pageno == 1) {
//                        mania(pointValuea, lastx);
//
//                        testView.setText(formmatedFloatValue);
//                    }
//
//                }
            }
            else
            {
                // movePos();
                // movePos(pointValuea,307,355,8,12,0);
                // mania(pointValuea,(float)14.0);
            }
        }
        if(sPageJ.voladdress[1].equals(device)){
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
            // int value = BigInteger(fir,16);
            float lasty = (float) 0.0;
            lasty = (float)(value/10.0);
            NumberFormat formatter = new DecimalFormat("00.0");

            String formmatedFloatValue = formatter.format(lasty);
            if((lasty > 9.9) && (lasty < 14.6)) {
//                if(testfView == null) {
//
//                }
//                else {
//                    if(sPageJ.pageno == 1) {
//                        manib(pointValueb, lasty);
//                        testfView.setText(formmatedFloatValue);
//                    }
//                }
            }
            else {
                // movePos(pointValueb,761,325,6,9,0);
                // mania(pointValueb,(float)14.0);
            }
        }
    }
    void  diskt(String device,String stat)
    {
        if(sPageJ.allDArray[10].equals(device)){
            //  int fir = Integer.parseInt(stat.substring(2,3));
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
            if((value> -1) && (value < 101)) {

//                if(seekBar!=null)
//                {
//                    seekBar.setProgress(value);
//                }
            }
        }


    }

   // 5aa511822fe10000000000010001000000003dd1 按摩3
    //   "1fe5","1fe6","1fe4","1fe1","1fe2","2fe5","2fe6","2fe4","2fe1","2fe2"}; //10 start [66]

    void tryzuoy(String device,String stat)
    {
        try {
            int myPosition1 = TransformUtils.findPosition(sPageJ.feedDArray, device + "1");

            int myPosition2 = TransformUtils.findPosition(sPageJ.feedDArray, device + "2");

            int myPosition3 = TransformUtils.findPosition(sPageJ.feedDArray, device + "3");

            int myPosition4 = TransformUtils.findPosition(sPageJ.feedDArray, device + "4");


            if (stat.equals("0000")) {
                if (myPosition1 != -1) {
                    testzuoyFeed(myPosition1, true);
                }

                if (myPosition2 != -1) {
                    testzuoyFeed(myPosition2, false);
                }

                if (myPosition3 != -1) {
                    testzuoyFeed(myPosition3, false);
                }

                if (myPosition4 != -1) {
                    testzuoyFeed(myPosition4, false);
                }

            }
            if (stat.equals("0001")) {

                if (myPosition1 != -1) {
                    testzuoyFeed(myPosition1, false);
                }

                if (myPosition2 != -1) {
                    testzuoyFeed(myPosition2, true);
                }

                if (myPosition3 != -1) {
                    testzuoyFeed(myPosition3, false);
                }

                if (myPosition4 != -1) {
                    testzuoyFeed(myPosition4, false);
                }
            }
            if (stat.equals("0002")) {

                if (myPosition1 != -1) {
                    testzuoyFeed(myPosition1, false);
                }

                if (myPosition2 != -1) {
                    testzuoyFeed(myPosition2, false);
                }

                if (myPosition3 != -1) {
                    testzuoyFeed(myPosition3, true);
                }

                if (myPosition4 != -1) {
                    testzuoyFeed(myPosition4, false);
                }
            }
            if (stat.equals("0003")) {

                if (myPosition1 != -1) {
                    testzuoyFeed(myPosition1, false);
                }

                if (myPosition2 != -1) {
                    testzuoyFeed(myPosition2, false);
                }

                if (myPosition3 != -1) {
                    testzuoyFeed(myPosition3, false);
                }

                if (myPosition4 != -1) {
                    testzuoyFeed(myPosition4, true);
                }
            }

        } catch
        (Exception ex) {

        }
    }
    void  diszuoy(String device,String stat) {
//        if(sPageJ.allDArray[22].equals(device)){
//            //  int fir = Integer.parseInt(stat.substring(2,3));
//            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
//            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
//            int value = fir * 16 + sec;
//
//
//            if((value > -1) && (value < 101)) {
//
//
        if ((sPageJ.pageno == 14) && device.equals("2fe4")) { //2fe4 value

             tryzuoy(device,stat);
        }
        if ((sPageJ.pageno == 15) && device.equals("2fe1")) { //2fe4 value

            tryzuoy(device,stat);
        }
        if ((sPageJ.pageno == 16) && device.equals("2fe2")) { //2fe4 value

            tryzuoy(device,stat);
        }

        if ((sPageJ.pageno == 10) && device.equals("1fe4")) { //2fe4 value

            tryzuoy(device,stat);
        }
        if ((sPageJ.pageno == 11) && device.equals("1fe1")) { //2fe4 value

            tryzuoy(device,stat);
        }
        if ((sPageJ.pageno == 12) && device.equals("1fe2")) { //2fe4 value

            tryzuoy(device,stat);
        }
    }

    void  diswait(String device,String stat)
    {
        if(sPageJ.voladdress[4].equals(device)){
            //  int fir = Integer.parseInt(stat.substring(2,3));
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
           // csView.setText(""+value);

            if((value > -1) && (value < 301)) {


                if((sPageJ.pageno == 29)||(sPageJ.pageno == 229)) {

                 //   csImgView.setImageDrawable(getDrawable(R.drawable.azz));
                    csView.setText(""+value);
//                    csImgView.setPivotX((float)convertW(7));
//                    csImgView.setPivotY((float)convertH(105));
//                    csImgView.setRotation((value-120)*90/80);
                  //  isseek1feed = true;
                  //  seekBar1.setProgress(value);

                    // isseek1feed = true;
                  //  csView.setText(""+value);
                }


            }

        }
        if(sPageJ.voladdress[5].equals(device)){
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;
            airqView.setText(""+value);
            if((value > -1) && (value < 150)) {

                if((sPageJ.pageno == 29)||(sPageJ.pageno == 229)) {
                 //   isseek2feed = true;
                    //  seekBar2.invalidate();
                 //   seekBar2.setProgress(value);
                    if(value >= 30)
                    {
                       // airqImgView.setImageDrawable(getDrawable(R.mipmap.p3));
                        airlocView.setText("空气质量：优");
                    }
                    else
                    {
                        airlocView.setText("空气质量：良");
                      //  airqImgView.setImageDrawable(getDrawable(R.mipmap.p4));
                    }

                    // seekBar2.invalidate();
                    // refseekbar2();
                    //createSeek32();
                }


            }


        }
    }

    void  disvol(String device,String stat)
    {
        if(sPageJ.allDArray[22].equals(device)){
            //  int fir = Integer.parseInt(stat.substring(2,3));
            int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
            int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
            int value = fir * 16 + sec;


            if((value > -1) && (value < 101)) {


                if((sPageJ.pageno == 52)||(sPageJ.pageno == 252)) {

                    isseek1feed = true;
                    seekBar1.setProgress(value);

                    // isseek1feed = true;
                }


            }

        }
            if(sPageJ.allDArray[23].equals(device)){
                int fir = Integer.parseInt(CRC16.convert16(stat.substring(2,3)));
                int sec = Integer.parseInt(CRC16.convert16(stat.substring(3)));
                int value = fir * 16 + sec;

                if((value > -1) && (value < 101)) {

                    if((sPageJ.pageno == 52)||(sPageJ.pageno == 252)) {
                        isseek2feed = true;
                        //  seekBar2.invalidate();
                        seekBar2.setProgress(value);

                        // seekBar2.invalidate();
                        // refseekbar2();
                        //createSeek32();
                    }


                }


            }
    }
    protected int rconvertH(int old) {
        DisplayMetrics dm = new DisplayMetrics();

        getWindowManager().getDefaultDisplay().getMetrics(dm);

        int screenWidth = dm.widthPixels;

        int screenHeight = dm.heightPixels;

        int newx = (600 * old) / screenHeight;

        return newx;

    }

    protected View createButton(int index) {
        final Button btn = new Button(this);
        btn.setId(index++);
        Log.d("da", "id is" + btn.getId());

        btn.setWidth(40);
        btn.setHeight(100);
        //GridLayout.LayoutParams mParams = new GridLayout.LayoutParams(
        //btn.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
        //       LinearLayout.LayoutParams.WRAP_CONTENT));
        // btn.set
        // btn.setLayoutParams(new GridLayout.LayoutParams(GridLayout.LayoutParams.MATCH_PARENT, GridLayout.LayoutParams.MATCH_PARENT));
        btn.setText("okc");
        return btn;
    }

    public  void addmezisxx()
    {


        Rect tmprect = new Rect() ;
        Rect tmprecto = new Rect() ;
        int tmp =sPageJ.allRect.length;
        maxC = tmp ;
        for (int w=0; w<tmp;w++) {
            // tmprecto = convertRect(sPageJallRect[w]);
            int  nType =  sPageJ.typeArray[w] ;
            if(nType == 16)
            {
                tmprecto = sPageJ.allRect[w];
                //  JBtnView mezii = new JBtnView(startActivity.this);
                Button mezii = new Button(this);
                FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(convertW(tmprecto.width()), convertH(tmprecto.height()));

               // headParams.leftMargin = convertW(tmprecto.left);
                headParams.leftMargin = convertW(0);
                //  headParams.topMargin = convertHn(136);
                headParams.topMargin = convertH(tmprecto.top);

                mezii.setLayoutParams(headParams);
             //   mezii.setBackground(getDrawable(sPageJ.offArray[0]));
                mezii.setBackground(getDrawable(sPageJ.offArray[w]));
              //  mezii.setBackground(sPageJ.offArray[w]);
                String addr = sPageJ.feedDArray[w];

                String tmpS = sPageJ.feedMap.get(addr);

             //   mezii.type = sPageJ.nodeArray[w];
                ButtonListener btnx = new ButtonListener();
              mezi.setOnTouchListener(btnx);
                mezii.setId(w + 1);

                frame.addView(mezii, w);


            }
            else {
                tmprecto = sPageJ.allRect[w];
                //  JBtnView mezii = new JBtnView(startActivity.this);
                MeziView mezii = new MeziView(startActivity.this);

                // mezi.setOnTouchListener(new OnTouchListener() {
                //  @Override
                // public boolean onTouch(View view, MotionEvent event) {


                //  mezi.bitmapX = 100;
                //  mezi.bitmapY = 0;
                mezii.mleft = convertW(tmprecto.left);
                mezii.mtop = convertH(tmprecto.top);
                mezii.mwidth = convertW(tmprecto.width());
                mezii.mheight = convertH(tmprecto.height());

                mezii.mRes = sPageJ.offArray[w];
                String addr = sPageJ.feedDArray[w];
                //  boolean bool1 = sPageJ.feedMap.containsKey(addr);
                String tmpS = sPageJ.feedMap.get(addr);
                // boolean bool2 = (tmpS == null)? false:(tmpS.equals("0001"));


                mezii.type = sPageJ.nodeArray[w];
                //   mezii.setClickable(true);

                // mezi.setTag(allCmd.toString());
                mezii.setId(w + 1);
                // frame.setTag(allCmd.toString());
                // mezii.setOnTouchListener(new TouchListenerx());

                //  frame.addView(mezi,0);
                //  frame.setBackgroundResource(sPageJtatus.pageback);
                // frame.addView(mezii);
                frame.addView(mezii, w);
                //   if(bool1 && bool2)
                // {
                //     mezii.mRes = sPageJ.onArray[w];
         //         mezii.repaint();
            }
            //testFeed(w,true);
            //  }
            //  testFeed(6);
            // frame.getChildAt()
        }
    }

    public  void addmezis()
    {


        Rect tmprect = new Rect() ;
        Rect tmprecto = new Rect() ;
        int tmp =sPageJ.allRect.length;
        maxC = tmp ;
        TouchListenerx othertouch = new TouchListenerx();
        ButtonListener btnx = new ButtonListener();
        for (int w=0; w<tmp;w++) {
            // tmprecto = convertRect(sPageJallRect[w]);
            int  nType =  sPageJ.typeArray[w] ;


                if (nType == 16) {
                    tmprecto = sPageJ.allRect[w];
                    //  JBtnView mezii = new JBtnView(startActivity.this);
                    Button mezii = new Button(this);
                    // mezii.setStateListAnimator(null);
                    FrameLayout.LayoutParams headParams = new FrameLayout.LayoutParams(convertW(tmprecto.width()), convertH(tmprecto.height()));

                    headParams.leftMargin = convertW(tmprecto.left);
                    //  headParams.leftMargin = convertW(0);
                    //  headParams.topMargin = convertHn(136);
                    headParams.topMargin = convertH(tmprecto.top);

                    mezii.setLayoutParams(headParams);

                    //  mezii.setBackground(getDrawable(sPageJ.onArray[w]));
                    mezii.setBackground(getDrawable(sPageJ.offArray[w]));
                    String addr = sPageJ.feedDArray[w];

                    String tmpS = sPageJ.feedMap.get(addr);

                    //   mezii.type = sPageJ.nodeArray[w];
                    //    ButtonListener btnx = new ButtonListener();
                    mezii.setOnTouchListener(btnx);
                    mezii.setId(w + 1);
                    // frame.addView(mezii, headParams);
                    frame.addView(mezii, w);

                    //  mezii.repaint();
                } else {
                    tmprecto = sPageJ.allRect[w];
                    //  JBtnView mezii = new JBtnView(startActivity.this);
                    MeziView mezii = new MeziView(startActivity.this);

                    // mezi.setOnTouchListener(new OnTouchListener() {
                    //  @Override
                    // public boolean onTouch(View view, MotionEvent event) {


                    //  mezi.bitmapX = 100;
                    //  mezi.bitmapY = 0;
                    mezii.mleft = convertW(tmprecto.left);
                    mezii.mtop = convertH(tmprecto.top);
                    mezii.mwidth = convertW(tmprecto.width());
                    mezii.mheight = convertH(tmprecto.height());

                    mezii.mRes = sPageJ.offArray[w];
                    String addr = sPageJ.feedDArray[w];
                    //  boolean bool1 = sPageJ.feedMap.containsKey(addr);
                    //   String tmpS = sPageJ.feedMap.get(addr);
                    // boolean bool2 = (tmpS == null)? false:(tmpS.equals("0001"));
                    boolean bool1 = sPageJ.feedMap.containsKey(addr);
                    String tmpS = sPageJ.feedMap.get(addr);
                    boolean bool2 = (tmpS == null) ? false : (tmpS.equals("0001"));

                    mezii.type = sPageJ.nodeArray[w];
                    //   mezii.setClickable(true);

                    // mezi.setTag(allCmd.toString());
                    mezii.setId(w + 1);
                    //    mezi.setOnTouchListener(othertouch);
                    //   mezi.setOnTouchListener(new TouchListenerx());
                    // frame.setTag(allCmd.toString());
                    // mezii.setOnTouchListener(new TouchListenerx());

                    //  frame.addView(mezi,0);
                    //  frame.setBackgroundResource(sPageJtatus.pageback);
                    // frame.addView(mezii);
                    frame.addView(mezii, w);
                    //   if(bool1 && bool2)
                    // {
                    //     mezii.mRes = sPageJ.onArray[w];
                    //  mezii.repaint();
                    if (bool1 && bool2) {
                        mezii.mRes = sPageJ.onArray[w];
                        mezii.repaint();
                        //testFeed(w,true);ff
                    } else {
                        mezii.mRes = sPageJ.offArray[w];
                        mezii.repaint();
                    }

                }
            }
//            testFeed(w,true);
//              }
//              testFeed(6);
//             frame.getChildAt()
       // }
    }

    public  void addmezisolddd()
    {


        Rect tmprect = new Rect() ;
        Rect tmprecto = new Rect() ;
        int tmp =sPageJ.allRect.length;
        maxC = tmp ;
        for (int w=0; w<tmp;w++) {
            // tmprecto = convertRect(sPageJallRect[w]);


            tmprecto = sPageJ.allRect[w];
          //  JBtnView mezii = new JBtnView(startActivity.this);
            MeziView mezii = new MeziView(startActivity.this);

            // mezi.setOnTouchListener(new OnTouchListener() {
            //  @Override
            // public boolean onTouch(View view, MotionEvent event) {



            //  mezi.bitmapX = 100;
            //  mezi.bitmapY = 0;
            mezii.mleft = convertW(tmprecto.left);
            mezii.mtop = convertH(tmprecto.top);
            mezii.mwidth = convertW(tmprecto.width());
            mezii.mheight = convertH(tmprecto.height());

            mezii.mRes = sPageJ.offArray[w];
            String addr = sPageJ.feedDArray[w];
            //  boolean bool1 = sPageJ.feedMap.containsKey(addr);
            String tmpS = sPageJ.feedMap.get(addr);
            // boolean bool2 = (tmpS == null)? false:(tmpS.equals("0001"));


            mezii.type = sPageJ.nodeArray[w];
            //   mezii.setClickable(true);

            // mezi.setTag(allCmd.toString());
            mezii.setId(w + 1);
            // frame.setTag(allCmd.toString());
            // mezii.setOnTouchListener(new TouchListenerx());

            //  frame.addView(mezi,0);
            //  frame.setBackgroundResource(sPageJtatus.pageback);
            // frame.addView(mezii);
            frame.addView(mezii,w);
            //   if(bool1 && bool2)
            // {
            //     mezii.mRes = sPageJ.onArray[w];
            mezii.repaint();
            //testFeed(w,true);
            //  }
            //  testFeed(6);
            // frame.getChildAt()
        }
    }


    private void openApp(String packageName, String actName , Context cx) {
//        PackageInfo pi = cx.getPackageManager().getPackageInfo(packageName, 0);
//
//        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
//        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
//        resolveIntent.setPackage(pi.packageName);
//
//        List<ResolveInfo> apps = pm.queryIntentActivities(resolveIntent, 0);
//
//        ResolveInfo ri = apps.iterator().next();
//        if (ri != null ) {
//            String packageName = ri.activityInfo.packageName;
//            String className = ri.activityInfo.name;
//
//            Intent intent = new Intent(Intent.ACTION_MAIN);
//            intent.addCategory(Intent.CATEGORY_LAUNCHER);
//
//            ComponentName cn = new ComponentName(packageName, className);
//
//            intent.setComponent(cn);
        // startActivity(intent);

        Intent intent=new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setComponent(new ComponentName(packageName, actName));
        cx.startActivity(intent);
    }

    private  final  Runnable runnable=new Runnable() {
        @Override
        public void run() {

            //   MainActivityf myown =mActivity.get();

            if (myowna != null) {
          //      int tmp = readFeedback();

               //  if(touchDownflag>0) {
                //    touchDownflag --;
                    handler.postDelayed(runnable, 150); // readFeedback();//
               //  }
            }
        }


    };

    private void renew()
    {
        //  refreshui(sPageJpageno);
        //  reciteallui("");

        return;
    }
//    public int readFeedback() {
//        String tmpstr = "";
//        String feedCamdstr = "";
//        String feedCamdFalgstr = "";
//        try {
//            int read_count = uartJni.read(fd, read_buf, read_buf.length);
//            if ((read_count < 0)||(read_count > 60)) {
//                read_count = 0; }
//            tmpstr = toHex(read_buf, read_count).toString();
//            if (!tmpstr.equals("")) {
//                Message cmdmsg = new Message();
//                cmdmsg.what = 1;
//                Bundle bcmd = new Bundle();
//                int index, index82, index5a;
//                int cmdlenght,feedCamdstrlenght,head;
//                int tmpstrlenght = read_buf.length;
//                index=index5a = tmpstr.indexOf("5aa5");
//                index82 = tmpstr.indexOf("82");
//                if(( index != -1) &&(index5a == index82-6)) {
//                    cmdlenght = ((int) tmpstr.charAt(index + 4) - 48) * 16 + (int) tmpstr.charAt(index + 5) - 48;
//                    feedCamdstrlenght=(cmdlenght + 3) * 2;
//                    if(tmpstr.length()>=feedCamdstrlenght) {
//                        feedCamdstr = tmpstr.substring(index, index + feedCamdstrlenght);
//                        bcmd.putString("alltext", feedCamdstr);
//                        cmdmsg.setData(bcmd);
//                        boolean xx = uHandler.sendMessage(cmdmsg);
//                    }
//                }
//                index=index5a = tmpstr.indexOf("5aa5",index+20);
//                if(( index != -1) &&(index5a >=20)) {
//                    cmdlenght = ((int) tmpstr.charAt(index + 4) - 48) * 16 + (int) tmpstr.charAt(index + 5) - 48;
//                    feedCamdstrlenght=(cmdlenght + 3) * 2;
//                    if(tmpstr.length()>=feedCamdstrlenght) {
//                        feedCamdstr = tmpstr.substring(index, index + feedCamdstrlenght);
//                        bcmd.putString("alltext", feedCamdstr);
//                        cmdmsg.setData(bcmd);
//                        boolean xx = uHandler.sendMessage(cmdmsg);
//                    }
//                }
//                index=index5a = tmpstr.indexOf("5aa5",index+20);
//                if(( index != -1) &&(index5a >=40)) {
//                    cmdlenght = ((int) tmpstr.charAt(index + 4) - 48) * 16 + (int) tmpstr.charAt(index + 5) - 48;
//                    feedCamdstrlenght=(cmdlenght + 3) * 2;
//                    if(tmpstr.length()>=feedCamdstrlenght) {
//                        feedCamdstr = tmpstr.substring(index, index + feedCamdstrlenght);
//                        bcmd.putString("alltext", feedCamdstr);
//                        cmdmsg.setData(bcmd);
//                        boolean xx = uHandler.sendMessage(cmdmsg);
//                    }
//                }
//
//
//        /*    index = tmpstr.indexOf("82");
//            if (index >= 6) {
//                index = index-6;
//                if(index != -1){
//                    cmdlenght = ((int) tmpstr.charAt(index + 4) - 48) * 16 + (int) tmpstr.charAt(index + 5) - 48;
//                    feedCamdstr = tmpstr.substring(index, index + (cmdlenght + 3) * 2);
//                    bcmd.putString("alltext", feedCamdstr);
//                    cmdmsg.setData(bcmd);
//                    boolean xx = uHandler.sendMessage(cmdmsg);
//                }
//            }*/
//            }
//        } catch (Exception ex) {
//            // renew();
//            return  0;
//        }
//
//        return 1;
//    }

    public int readNewFeedbackxx(String tmpstr) {
//        String tmpstr = "";
        String feedCamdstr = "";
//        String feedCamdFalgstr = "";
        tmpstr = "5aa50d8240010001000000000000bb1a";

        try {
//            int read_count = uartJni.read(fd, read_buf, read_buf.length);
//            if ((read_count < 0)||(read_count > 60)) {
//                read_count = 0; }
//            tmpstr = toHex(read_buf, read_count).toString();
             //forwardM(tmpstr);
            if (!tmpstr.equals("")) {
                Message cmdmsg = new Message();
                cmdmsg.what = 1;
                Bundle bcmd = new Bundle();
                int index, index82, index5a;
                int cmdlenght,feedCamdstrlenght,head;
                int tmpstrlenght = read_buf.length;
                index=index5a = tmpstr.indexOf("5aa5");
                index82 = tmpstr.indexOf("82");
                if(( index != -1) &&(index5a == index82-6)) {
                    cmdlenght = ((int) tmpstr.charAt(index + 4) - 48) * 16 + (int) tmpstr.charAt(index + 5) - 48;
                    feedCamdstrlenght=(cmdlenght + 3) * 2;
                    if(tmpstr.length()>=feedCamdstrlenght) {
                        feedCamdstr = tmpstr.substring(index, index + feedCamdstrlenght);
                        bcmd.putString("alltext", feedCamdstr);
                        cmdmsg.setData(bcmd);
                        //forwardM(feedCamdstr);
                        boolean xx = uHandler.sendMessage(cmdmsg);

                    }
                }
                index=index5a = tmpstr.indexOf("5aa5",index+20);
                if(( index != -1) &&(index5a >=20)) {
                    cmdlenght = ((int) tmpstr.charAt(index + 4) - 48) * 16 + (int) tmpstr.charAt(index + 5) - 48;
                    feedCamdstrlenght=(cmdlenght + 3) * 2;
                    if(tmpstr.length()>=feedCamdstrlenght) {
                        feedCamdstr = tmpstr.substring(index, index + feedCamdstrlenght);
                        bcmd.putString("alltext", feedCamdstr);
                        cmdmsg.setData(bcmd);
                       // forwardM(feedCamdstr);
                        boolean xx = uHandler.sendMessage(cmdmsg);
                    }
                }
                index=index5a = tmpstr.indexOf("5aa5",index+20);
                if(( index != -1) &&(index5a >=40)) {
                    cmdlenght = ((int) tmpstr.charAt(index + 4) - 48) * 16 + (int) tmpstr.charAt(index + 5) - 48;
                    feedCamdstrlenght=(cmdlenght + 3) * 2;
                    if(tmpstr.length()>=feedCamdstrlenght) {
                        feedCamdstr = tmpstr.substring(index, index + feedCamdstrlenght);
                        bcmd.putString("alltext", feedCamdstr);
                       // forwardM(feedCamdstr);
                        cmdmsg.setData(bcmd);
                        boolean xx = uHandler.sendMessage(cmdmsg);
                    }
                }


        /*    index = tmpstr.indexOf("82");
            if (index >= 6) {
                index = index-6;
                if(index != -1){
                    cmdlenght = ((int) tmpstr.charAt(index + 4) - 48) * 16 + (int) tmpstr.charAt(index + 5) - 48;
                    feedCamdstr = tmpstr.substring(index, index + (cmdlenght + 3) * 2);
                    bcmd.putString("alltext", feedCamdstr);
                    cmdmsg.setData(bcmd);
                    boolean xx = uHandler.sendMessage(cmdmsg);
                }
            }*/
            }
        } catch (Exception ex) {
            // renew();
            return  0;
        }

        return 1;
    }


    class LockScreenReceiver extends BroadcastReceiver {
        // private WeakReference<GridView> gridView;

        public LockScreenReceiver() {
            // gridView = new WeakReference<GridView>(gv);
        }


        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
//                Intent lockIntent = new Intent(Constant.LOCK_SCREEN_ACTION);
//                lockIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
//                        | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
//
//                context.startActivity(lockIntent);
               // timeStart();
                touchjmp("");
//                long now = SystemClock.uptimeMillis();
//
//                KeyEvent down = new KeyEvent(now, now, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_1, 0);
//
//                InputManager.getInstance().injectInputEvent(down, InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
//
//                KeyEvent up = new KeyEvent(now, now, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_1, 0);
//
//                InputManager.getInstance().injectInputEvent(up, InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
//                Instrumentation mInst = new Instrumentation();
//
//                mInst.sendKeyDownUpSync(KeyEvent.KEYCODE_1);

            } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                // do other things if you need
            } else if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
                // do other things if you need
            }
        }
    }

//    public class ActionReceiver extends BroadcastReceiver {
//
//        private static final String ACTION = "com.madreain.broadcast.MyReceiverFilter";
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            if (intent.getAction().equals(ACTION) ){
//                //接收固定广播进行处理
//
//            }
//        }
//    }

    public int readNewFeedback(String tmpstr) {
//        String tmpstr = "";
        String feedCamdstr = "";
//        String feedCamdFalgstr = "";
     //   tmpstr = "5aa50d8240010001000000000000bb1a";
     //  tmpstr = "5aa51d820ee100010000000000000000000000000000000000000000000153cd";
        try {
            Message cmdmsg = Message.obtain();
            cmdmsg.what = 1;
            Bundle bcmd = new Bundle();
            bcmd.putString("alltext", tmpstr);
            // forwardM(feedCamdstr);
            cmdmsg.setData(bcmd);
            boolean xx = uHandler.sendMessage(cmdmsg);

        }catch (Exception ex) {
            // renew();
            return  0;
        }

        return 1;
    }
    private void muteaudioa(boolean xxx)
    {
        callMenu.muteAudioFocus(this,xxx);
    }

    private void lastsong()
    {

//        Intent freshIntent02 = new Intent();
//
//        freshIntent02.setAction(SERVICECMD);
//
//        freshIntent02.putExtra(CMDNAME, "previous");
//
//        sendBroadcast(freshIntent02);
//        if(ismute) {
//           // bindMusicService();
//            if (mBinder != null) {
//                mBinder.pre();
//                String songname = mBinder.getName() + mBinder.getCurrenPostion();
//                String tmpsong = songname;
//            }
//        }

        callMenu.toast(startActivity.this, "请确定播放器及播放列表确定上一首");

    }

    private void nextsong()
    {

//        Intent freshIntent = new Intent();
////
////        freshIntent.setAction(SERVICECMD);
////
////        freshIntent.putExtra(CMDNAME, "next");
////
////        sendBroadcast(freshIntent);
//        if(ismute) {
//            //bindMusicService();
//            if (mBinder != null) {
//                mBinder.next();
//                String songname = mBinder.getName() + mBinder.getCurrenPostion();
//                String tmpsong = songname;
//            }
//        }

        callMenu.toast(startActivity.this, "请确定播放器及播放列表确定下一首");

    }

    private void plasong()
    {

        Intent intent = new Intent(SERVICECMD);

        intent.putExtra(CMDNAME, "play");

        sendBroadcast(intent);

//        mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
//
////获取系统最大音量
//
//        int maxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//
//// 获取设备当前音量
//
//        int currentVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
//
//// 设置seekbar的最大值
//
//        vol_seekbar.setMax(maxVolume);
//
//// 显示音量
//
//        vol_seekbar.setProgress(currentVolume);
//
//        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0); //progress:音量绝对值


    }
    private void pausong()

    {

        Intent intent04 = new Intent(SERVICECMD);

        intent04.putExtra(CMDNAME, "stop");

        sendBroadcast(intent04);


    }

    private void exitapp()
    {
        this.finish();
        System.exit(0);

    }

    private void allapps()
    {

        //this.finish();
       // System.exit(0);
        Intent intent = new Intent(startActivity.this, gActivity.class);
        startActivity(intent);
    }



    public static void saveBmp2Gallery(Context cont,Bitmap bmp, String picName) {

        String fileName = null;
        //系统相册目录
        String galleryPath= Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM;
               // +File.separator+"Camera"+File.separator;


        // 声明文件对象
        File file = null;
        // 声明输出流
        FileOutputStream outStream = null;

        try {
            // 如果有目标文件，直接获得文件对象，否则创建一个以filename为名称的文件
            file = new File(galleryPath, picName+ ".jpg");

            // 获得文件相对路径
            fileName = file.toString();
            // 获得输出流，如果文件中有内容，追加内容
            outStream = new FileOutputStream(fileName);
            if (null != outStream) {
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            }

        } catch (Exception e) {
            e.getStackTrace();
        }finally {
            try {
                if (outStream != null) {
                    outStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
}//通知相册更新
          MediaStore.Images.Media.insertImage(cont.getContentResolver(),
                bmp, fileName, null);
//        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//        Uri uri = Uri.fromFile(file);
//        intent.setData(uri);
//        mContext.sendBroadcast(intent);
//
//     /   ToastUtil.show("图片保存成功");

    }



    private int execfun(String fun,String fun1)
    {
        if(!fun1.isEmpty())
        {
            if((!fun1.equals("")) && (!fun.equals("jmp"))) {
                int result = 1;
                try {
                    if (lonlyone == 0) {
                        openApp(fun, fun1, startActivity.this);
                        lonlyone = 1;
                    }
                    // onlyone = 0;
                    // return true;
                } catch (Exception e) {
                    callMenu.toast(startActivity.this, "请检查是否安装完整！");
                    // return  false;

                    result = 0;
                    //onlyone = 0;
                }
            }
//
//                if(fun.equals("pausesong") && fun1.equals("pause"))
//                {
//                    if(pauseonlyone == 0) {
//                        // allapps();
//                        if(ismute) {
//                            muteaudioa(ismute);
//                        }
//                        else {
//                            muteaudioa(ismute);
//                        }
//                        pauseonlyone = 1;
//                    }
//
//                    return 1;
//                }
//
//                if(fun.equals("pausesong") && fun1.equals("lasts"))
//                {
//                    if(lastsonlyone == 0) {
//                        // allapps();
//                         lastsong();
//                        lastsonlyone = 1;
//                    }
//
//                    return 1;
//                }
//
//                if(fun.equals("pausesong") && fun1.equals("nexts"))
//                {
//                    if(nextsonlyonce == 0) {
//                        // allapps();
//                        nextsong();
//                        nextsonlyonce = 1;
//                    }
//
//                    return 1;
//                }

            if(fun.equals("jmp") )
            {
                String jmpstr = fun1;
                if(jmpstr.equals("0"))
                 {
                     if(havajmp == 0) {
                         sendStart("10030000");
                     Message msg = Message.obtain();
                     msg.what = 3;
                     String cmdOne = "0";
                     msg.obj = cmdOne;
                     Bundle bundle = new Bundle();
                     bundle.putString("jmppageno",cmdOne);

                     msg.setData(bundle);

                     mHandler.sendMessage(msg);


                         havajmp = 1;
                     }
                }




                return 1;
            }
                return 1;

            }

        else {

            if (fun.equals("exitapp")) {

                if(exitapponlyone == 0) {
                    exitapp();
                    exitapponlyone = 1;
                }

                // onlyone = 0;
                return 1;
            }


            if (fun.equals("allapps")) {
                if (allappsonlyone == 0) {
                    allapps();
                    allappsonlyone = 1;
                }

                return 1;
            }

        }
        return  1;

    }

    private class TouchListenerx implements View.OnTouchListener {
        private boolean longClicked;
        private boolean xlongClicked = false;
        private boolean upClicked = false;
        private int downtimes = 0;
        private int uptimes = 0;
        private int failTime;
        //private IBackService xBackService;
//        private TouchListenerx(IBackService abak) {
//         //   xBackService = abak;
//        }

        private TouchListenerx() {
            //   xBackService = abak;
        }



        int getCurSel(Rect[] allrect ,int x,int y)
        {

            //  if (tempRect.contains((int) x, (int) (y)))
            Rect tmprect = new Rect() ;
            Rect tmprecto = new Rect() ;
            int tmp = allrect.length;
            for (int w=0; w<tmp;w++)
            {
                tmprecto = convertRect(allrect[w]);
                if (tmprecto.contains(x,y))
                {
                    tmprect = tmprecto;
                    return  w;
                }
            }
            return  -1;
        }




        @Override
        public boolean onTouch(View v, MotionEvent event) {


            int x = (int) event.getX();

            int y = (int) event.getY();
//                if (!uartJnit.isFastClick()) {
//                    return true;
//                }
            currentPosition = getCurSel(sPageJ.allRect, x, y);

//                if((sPageJ.pageno ==0)&&(currentPosition == 4))
//                {
//                   // isdengpressed = 1;
//                }

            // Log.e("touchTAG", "view:" + v.getId());


            if (currentPosition != -1) {
                //  isSel++;
                String cmdOne = sPageJ.cmdArray[currentPosition];
                // String cmdTwo = sPageJ.actArray[currentPosition];
                int mmtype = pagestatus.typeArray[currentPosition];

                switch (mmtype)
                {
                    case 20:
                        if (mmtype == 20) {
                            Message msg = new Message();
//                        if(currentPosition == 1)
//                            touchDownflag=300;
//                        else
                            touchDownflag=3;
                            // uartJni.read(fd, read_buf, read_buf.length);
                            //  handler.postDelayed(runnable,100);
                            msg.what = 3;
                            msg.obj = cmdOne;
                            Bundle bundle = new Bundle();
                            bundle.putString("jmppageno", cmdOne);

                            msg.setData(bundle);

                            mHandler.sendMessage(msg);
                            // return false;
                        }
                        break;

                    case 41:
                        if (mmtype == 41) {

                            // if (event.getAction() == 1) {

                            //lonlyone = onlyone;

                            String cmdTwo = sPageJ.actArray[currentPosition];
                            execfun(cmdOne, cmdTwo);
                            //  }
//                        if (onlyone == lonlyone) {
//                            onlyone = (onlyone +1) % 99;
//                            String cmdTwo = sPageJ.actArray[currentPosition];
//                            execfun(cmdOne, cmdTwo);
//
//                        }
                            //     }
                            //   return true;
                        }

                        break;

                    case 19:
//                        if(mmtype == 19) {
//                            //String origin = "5AA50883192001001F"; //19E2
//                            String allCmdx = cmdheader;
//
//                            String tmpTmp = cmdOne;
//
//                            allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
//                            StringBuffer allCmd = CRC16.crc16x(allCmdx);
//                            final String cmd = allCmd.substring(0, 22);
//
//                        //xlongClicked = false;
//                            upClicked = false;
//                           // uartJni.read(fd, read_buf, read_buf.length);
//                            touchDownflag = 2;
//                            handler.postDelayed(runnable, 150);
//                            isDown = 1;
//                            new Thread() {
//                                public void run() {
//                                    super.run();
//
//
//                                    if (!xlongClicked) {
//                                        try {
//                                            //   if (uartJint != null) {
//                                            boolean isSendx = false;
//                                            if (downtimes < 1) {
//                                                downtimes = downtimes++;
//                                                isSendx = uartJnit.getInstance().sendCmds(cmd);
//
//                                               // longClicked = true;
//                                            }
//
//                                            //  Log.e("send TAG", "send down: " + cmd);
//                                            Message msg = new Message();
//                                            if (isSendx) {
//                                                msg.what = 1;
//
//                                                xlongClicked = true;
//
//                                                // readFeedbacko();
//
//                                                Log.e("send TAG", "send down" + cmd + "success");
//                                                // testsoFeed(currentPosition, false);
//                                            } else {
//
//
//                                                Log.e("TAG", "send down  :" + cmd + "failed!");
////
//                                            }
//                                            //    }
////
//                                        } catch (Exception e) {
//                                            e.printStackTrace();
//                                        }
//                                        try {
//                                            Thread.sleep((long) TIMER_INTERVAL);
//                                        } catch (InterruptedException e2) {
//                                            e2.printStackTrace();
//
//                                        }
//                                    }
//
//                                }
//                            }.start();
//
//                            return true;
//                        }
                             if(mmtype == 19) {
                                int action = event.getAction();

                                switch(action)
                                {
                                    case 0:
                                        String origin = "5AA50883192001001F"; //19E2
                                        String allCmdx = cmdheader;

                                        String tmpTmp = cmdOne;

                                        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
                                        StringBuffer allCmd = CRC16.crc16x(allCmdx);
                                        final String cmd = allCmd.substring(0, 22);

                                     //   xlongClicked = false;
                                        //  upClicked = false;
                                   //     uartJni.read(fd, read_buf, read_buf.length);
                                      //  touchDownflag = 3;
                                        // readFeedback();
                                     //    handler.postDelayed(runnable, 100);
                                        xlongClicked = false;
                                        isDown = 1;
                                        new Thread() {
                                            public void run() {
                                                super.run();


                                                if (!xlongClicked) {
                                                    try {
                                                        //   if (uartJint != null) {
                                                        boolean isSendx = false;
                                                        if (downtimes < 1) {
                                                            downtimes = downtimes++;
                                                       //     isSendx = uartJnit.getInstance().sendCmds(cmd);

                                                           // ComA.sendTxt(cmd);
                                                           ComA.sendHex(cmd);
                                                           xlongClicked = true;
                                                          //  SetLoopData(ComA,cmd);
                                                          //  ComA.setTxtLoopData(cmd);
                                                          //  xlongClicked = true;
                                                            Log.e("send TAG", "send down: " + cmd);
                                                            //testbtnFeed(currentPosition, false);
                                                        }
                                                        else
                                                        {

                                                        }

                                                        //
                                                        Message msg = new Message();
                                                        if (isSendx) {
                                                            msg.what = 1;



                                                            // readFeedbacko();

                                                            Log.e("down", "send down:" + cmd + "success");
                                                            // testsoFeed(currentPosition, false);

                                                        } else {


                                                           // Log.e("TAG", "send down  :" + cmd + "failed!");
//
                                                        }
                                                        //    }
//
                                                    } catch (Exception e) {
                                                       // e.printStackTrace();
                                                        Log.e("TAG", "send down  :" + cmd + "failed!");
                                                    }
                                                    try {
                                                        Thread.sleep((long) TIMER_INTERVAL);
                                                    } catch (InterruptedException e2) {
                                                        e2.printStackTrace();

                                                    }
                                                }

                                            }
                                        }.start();


                                   // break;

                                    default:


//                                        allCmdx = cmdheader;
//                                       // cmdOne.replace("2","3");
//                                       //   StringBuilder strb = new StringBuilder(cmdOne);
//                                        //strb.replace(2, 3, "3");
//                                         // cmdOne = strb.toString();
//                                        tmpTmp = cmdOne;
//
//                                        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
//                                      allCmd = CRC16.crc16x(allCmdx);
//                                         final String  xcmd = allCmd.substring(0, 22);
//
//                                        // longClicked = false;
//                                        upClicked = false;
//                                        //  Log.e("upupup", isMove + "");
//                                        isUp = 1;
//                                        isDown = 0;


                                        xlongClicked = false;

//                                        try {
//                                            Thread.sleep((long) TIMER_INTERVAL);
//                                        } catch (InterruptedException e2) {
//                                            e2.printStackTrace();
//
//                                        }

                                        // return false;

                                        break;


                                }




                                                  }
                          // break;
                         // return false;
                        break;
                    case 16:

                        //     if(mmtype == 16) {
//                                int action = event.getAction();
//
//                                switch(action)
//                                {
//                                    case 0:
//                                        String origin = "5AA50883192001001F"; //19E2
//                                        String allCmdx = cmdheader;
//
//                                        String tmpTmp = cmdOne;
//
//                                        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
//                                        StringBuffer allCmd = CRC16.crc16x(allCmdx);
//                                        final String cmd = allCmd.substring(0, 22);
//
//                                        longClicked = false;
//                                        //  upClicked = false;
//                                        uartJni.read(fd, read_buf, read_buf.length);
//                                        touchDownflag = 3;
//                                        // readFeedback();
//                                        //handler.postDelayed(runnable, 100);
//                                        isDown = 1;
//                                        new Thread() {
//                                            public void run() {
//                                                super.run();
//
//
//                                                if (!longClicked) {
//                                                    try {
//                                                        //   if (uartJint != null) {
//                                                        boolean isSendx = false;
//                                                        if (downtimes < 1) {
//                                                            downtimes = downtimes++;
//                                                            isSendx = uartJnit.getInstance().sendCmds(cmd);
//
//                                                            longClicked = true;
//                                                            Log.e("send TAG", "send down: " + cmd);
//                                                            testbtnFeed(currentPosition, false);
//                                                        }
//
//                                                        //
//                                                        Message msg = new Message();
//                                                        if (isSendx) {
//                                                            msg.what = 1;
//
//                                                            longClicked = true;
//
//                                                            // readFeedbacko();
//
//                                                            Log.e("down", "send down:" + cmd + "success");
//                                                            // testsoFeed(currentPosition, false);
//
//                                                        } else {
//
//
//                                                            Log.e("TAG", "send down  :" + cmd + "failed!");
////
//                                                        }
//                                                        //    }
////
//                                                    } catch (Exception e) {
//                                                        e.printStackTrace();
//                                                    }
//                                                    try {
//                                                        Thread.sleep((long) TIMER_INTERVAL);
//                                                    } catch (InterruptedException e2) {
//                                                        e2.printStackTrace();
//
//                                                    }
//                                                }
//
//                                            }
//                                        }.start();
//
//
//                                   // break;
//
//                                    case 1:
//
//
//                                        allCmdx = cmdheader;
//                                       // cmdOne.replace("2","3");
//                                       //   StringBuilder strb = new StringBuilder(cmdOne);
//                                        //strb.replace(2, 3, "3");
//                                         // cmdOne = strb.toString();
//                                        tmpTmp = cmdOne;
//
//                                        allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
//                                      allCmd = CRC16.crc16x(allCmdx);
//                                         final String  xcmd = allCmd.substring(0, 22);
//
//                                        // longClicked = false;
//                                        upClicked = false;
//                                        //  Log.e("upupup", isMove + "");
//                                        isUp = 1;
//                                        isDown = 0;
//
//
//                                        new Thread() {
//                                            public void run() {
//                                                super.run();
//
//
//                                                if (!upClicked) {
//                                                    String tmp = xcmd.substring(10, 11);
//                                                    if (tmp.equals("2")) {
//
//                                                        try {
//                                                            //getExchangeCmd()
//
//                                                            //          if ((iBackService != null) && (cmd.length() == 22)) {
//                                                            if (xcmd.length() == 22) {
//
//                                                                boolean isSendy = false;
//
//                                                                Log.e("upup", "send  dian:" + TransformUtils.getExchangeCmd(xcmd));
//
//                                                                if (uptimes < 1) {
//                                                                    uptimes = uptimes++;
//                                                                //    String tmp = xcmd.substring(10, 11);
//                                                                //     xcmd.replace("20","30");
//                                                                  //  allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
//                                                                 //   StringBuffer allCmd = CRC16.crc16x(allCmdx);
//                                                                 //   final String cmd = allCmd.substring(0, 22);
//
//                                                                    isSendy = uartJnit.getInstance().sendCmds(TransformUtils.getExchangeCmd(xcmd));
//                                                                    testbtnFeed(currentPosition, true);
//                                                                    upClicked = true;
//                                                                }
//                                                                Message msg = new Message();
//                                                                if (isSendy) {
//                                                                    msg.what = 1;
//                                                                    msg.obj = currentPosition;
//
//                                                                    upClicked = true;
//
//                                                                    //testsoFeed(currentPosition,true);
//
//                                                                    //readFeedback();
//                                                                    //  Log.e("TAG", "send dian:" + TransformUtils.getExchangeCmd(cmd) + "success");
//                                                                } else {
//
//
//                                                                    Log.e("TAG", "send dian " + xcmd + " failed!");
//
//                                                                }
//
//                                                            }
//                                                        } catch (Exception e) {
//                                                            e.printStackTrace();
//                                                        }
//                                                    }
//                                                }
//                                            }
//                                        }.start();
//
//                                        try {
//                                            Thread.sleep((long) TIMER_INTERVAL);
//                                        } catch (InterruptedException e2) {
//                                            e2.printStackTrace();
//
//                                        }
//
//                                        // return false;
//
//                                        break;
//
//
//                                }




                        //                          }
                        //   break;
                        //  return false;
                    default:
                        break;

                }


                return true;
            }



            return true;
            //  return false;
        }
    }

    class ButtonListener implements View.OnClickListener, View.OnTouchListener {

        private boolean longClicked;
        private boolean upClicked = false;
        private int downtimes = 0;
        private int uptimes = 0;
        private int failTime;
        public void onClick(View v) {

        }

        int currentPositionww = 0;

        int getCurSelx(Rect[] allrect ,int x,int y)
        {

            //  if (tempRect.contains((int) x, (int) (y)))
            Rect tmprect = new Rect() ;
            Rect tmprecto = new Rect() ;
            int tmp = allrect.length;
            for (int w=0; w<tmp;w++)
            {
                tmprecto = convertRect(allrect[w]);
                if (tmprecto.contains(x,y))
                {
                    tmprect = tmprecto;
                    return  w;
                }
            }
            return  -1;
        }

        public boolean onTouch(View v, MotionEvent event) {
            //    if(v.getId() == R.id.button1){
//                if(event.getAction() == MotionEvent.ACTION_UP){
//                    Log.d("test", "cansal button ---> cancel");
//                    mButton.setBackgroundResource(R.drawable.ic_launcher_foreground);
//                }
//                if(event.getAction() == MotionEvent.ACTION_DOWN){
//                    Log.d("test", "cansal button ---> down");
//                    mButton.setBackgroundResource(R.drawable.ic_launcher_background);
//                }
//

            Button mybtn =(Button) v;
//            int x = (int) event.getX();
//            int y = (int) event.getY();
//            currentPositionww = getCurSelx(sPageJ.allRect, x, y);

            currentPositionww = mybtn.getId() ;
            currentPositionww = currentPositionww -1;
            Log.e("touchTAG", "view:" + v.getId());


            String cmdOne = sPageJ.cmdArray[currentPositionww];
            // String cmdTwo = sPageJ.actArray[currentPosition];
            int mmtype = pagestatus.typeArray[currentPositionww];

            //     if (currentPositionww != -1) {
            int action = event.getAction();
            switch (action) {
                case 0:

                    String origin = "5AA50883192001001F"; //19E2
                    String allCmdx = cmdheader;

                    String tmpTmp = cmdOne;

                    allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
                    StringBuffer allCmd = CRC16.crc16x(allCmdx);
                    final String cmd = allCmd.substring(0, 22);

                    longClicked = false;
                    //  upClicked = false;
                    //  uartJni.read(fd, read_buf, read_buf.length);
                    touchDownflag = 3;
                    // readFeedback();
                    //handler.postDelayed(runnable, 100);
                    isDown = 1;
                    new Thread() {
                        public void run() {
                            super.run();
                            //  mButton.setBackgroundResource(R.drawable.ic_launcher_foreground);

                            if (!longClicked) {
                                try {
                                    //   if (uartJint != null) {
                                    boolean isSendx = false;

                                    if (downtimes < 1) {
                                        downtimes = downtimes++;


                                        //    currentPositionww

//                                        isSendx = uartJnit.getInstance().sendCmds(cmd);

                                        ComA.sendHex(cmd);
                                        //  SetLoopData(ComA,cmd);

                                        // longClicked = true;
                                        //  testsoFeed(currentPosition, true);
//                                                            Message msg = new Message();
//                                                             msg.what = 8;
//                                                                                            msg.obj = "cmdOne8";
//                                                                                             Bundle bundle = new Bundle();
//                                                                                             bundle.putInt("which", currentPosition);
//                                                                                            bundle.putBoolean("ifif",true);
//                                                             //                   bundle.putString("feedStatus", deviceStaus);
//                                                                                            msg.setData(bundle);
//                                                            //                                //  Integer.parseInt(pagestatus.cmdArray[1]);
//                                                                                             mHandler.sendMessage(msg);
                                        //  testsoFeed(currentPosition, true);
                                    }

                                    //  Log.e("send TAG", "send down: " + cmd);

                                    //  if (isSendx) {
                                    //  Message msg = new Message();

                                    //   runOnUiThread(testbtnFeed(currentPositionww,false));

                                    Message msg = new Message();
                                    msg.what = 0;
                                    Bundle bundle = new Bundle();
                                    bundle.putInt("which", currentPositionww);
                                    bundle.putBoolean("ifif",true);
                                    //                   bundle.putString("feedStatus", deviceStaus);
                                    msg.setData(bundle);
                                    uiSwitch.sendMessage(msg);
                                    longClicked = true;

                                    // readFeedbacko();

                                    //  testsoFeed(currentPosition, false);
                                    Log.e("btndown", "send down:" + cmd + "success");

//                                    } else {
//
//
//                                        Log.e("btnTAG", "send down  :" + cmd + "failed!");
////
//                                    }
                                    //    }
//
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                try {
                                    Thread.sleep((long) TIMER_INTERVAL);
                                } catch (InterruptedException e2) {
                                    e2.printStackTrace();

                                }
                            }
                            // testsoFeed();
                        }
                    }.start();
                    break;
                case 1:
                    allCmdx = cmdheader;

                    tmpTmp = cmdOne;

                    allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
                    allCmd = CRC16.crc16x(allCmdx);
                    final String  xcmd = allCmd.substring(0, 22);

                    // longClicked = false;
                    upClicked = false;
                    //  Log.e("upupup", isMove + "");
                    isUp = 1;
                    isDown = 0;
                    new Thread() {
                        public void run() {
                            super.run();
                            //  mButton.setBackgroundResource(R.drawable.ic_launcher_foreground);

                            if (!upClicked) {
                                String tmp = xcmd.substring(10, 11);
                                if (tmp.equals("2")) {

                                    try {
                                        //getExchangeCmd()

                                        //          if ((iBackService != null) && (cmd.length() == 22)) {
                                        if (xcmd.length() == 22) {

                                            boolean isSendy = false;

                                            //      Log.e("upup", "send  dian:" + TransformUtils.getExchangeCmd(xcmd));

                                            if (uptimes < 1) {
                                                uptimes = uptimes++;

//                                                    Message msg = new Message();
//                                                    msg.what = 1;
//                                                    Bundle bundle = new Bundle();
//                                                    bundle.putInt("which", currentPositionww);
//                                                    bundle.putBoolean("ifif", true);
//                                                    //                   bundle.putString("feedStatus", deviceStaus);
//                                                    msg.setData(bundle);
//                                                    uiSwitch.sendMessage(msg);
//                                                isSendy = uartJnit.getInstance().sendCmds(TransformUtils.getExchangeCmd(xcmd));

                                                ComA.sendHex(TransformUtils.getExchangeCmd(xcmd));
                                                Log.e("btndian", "send dian:" + TransformUtils.getExchangeCmd(xcmd) + "success");
                                                // SetLoopData(ComA,xcmd);
                                                startActivity.this.runOnUiThread(new Runnable() {
                                                    public void run() {
                                                        testbtnFeed(currentPositionww,false);
                                                    }
                                                });
                                                //    upClicked = true;
//                                                                    Message msg = new Message();
//                                                                     msg.what = 8;
//                                                                                            msg.obj = "cmdOne8";
//                                                                                             Bundle bundle = new Bundle();
//                                                                                             bundle.putInt("which", currentPosition);
//                                                                                            bundle.putBoolean("ifif",false);
//                                                             //                   bundle.putString("feedStatus", deviceStaus);
//                                                                                            msg.setData(bundle);
//                                                            //                                //  Integer.parseInt(pagestatus.cmdArray[1]);
//                                                                                             mHandler.sendMessage(msg);
                                            }
//                                            Message msgxx = new Message();
//                                            if (isSendy) {
//                                                msgxx.what = 1;
//                                                msgxx.obj = currentPosition;
//
//                                                upClicked = true;
//
//                                                //   testsoFeed(currentPosition,true);
//
//                                                //readFeedback();
//                                                Log.e("btnTAG", "send dian:" + TransformUtils.getExchangeCmd(xcmd) + "success");
//
//                                            } else {
//
//
//                                                Log.e("btnTAG", "send dian " + TransformUtils.getExchangeCmd(xcmd) + " failed!");
//
//                                            }

                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    try {
                                        Thread.sleep((long) TIMER_INTERVAL);
                                    } catch (InterruptedException e2) {
                                        e2.printStackTrace();

                                    }
                                }
                            }

                        }
                    }.start();
                    break;

                default:
//                        new Thread() {
//                            public void run() {
//                                super.run();
//                                //  mButton.setBackgroundResource(R.drawable.ic_launcher_foreground);
//                                Message msg = new Message();
//                                msg.what = 1;
//                                Bundle bundle = new Bundle();
//                                bundle.putInt("which", currentPositionww);
//                                bundle.putBoolean("ifif", true);
//                                //                   bundle.putString("feedStatus", deviceStaus);
//                                msg.setData(bundle);
//                                uiSwitch.sendMessage(msg);
//
//                            }
//                        }.start();
                    break;

                // }

//                switch(action)
//                {
//                    case 0:
//
//                        new Thread() {
//                            public void run() {
//                                super.run();
//
//
//                                //    }
////
//                                mButton.setBackgroundResource(R.drawable.ic_launcher_foreground);
//
//                                    try {
//                                        Thread.sleep((long) 500);
//                                    } catch (InterruptedException e2) {
//                                        e2.printStackTrace();
//
//                                    }
//
//                }
//            }.start();
//
//
//
//
//                        break;
//
//                    case 1:
//
//
//
//                        new Thread() {
//                            public void run() {
//                                super.run();
//
//
//                                mButton.setBackgroundResource(R.drawable.ic_launcher_background);
//
//
//
//                        try {
//                            Thread.sleep((long)500);
//                        } catch (InterruptedException e2) {
//                            e2.printStackTrace();
//
//                        }
//                }
//            }.start();
//                        // return false;
//
//                        break;
//
//                    default :
//
//                        mButton.setBackgroundResource(R.drawable.ic_launcher_background);
//
//                        break;
//                }


                //   }

            }
            return  true;

        }
    }

    private class SerialControl extends SerialHelper {

        //		public SerialControl(String sPort, String sBaudRate){
//			super(sPort, sBaudRate);
//		}
        public SerialControl(){
        }

        @Override
        protected void onDataReceived(final ComBean ComRecData)
        {
            //数据接收量大或接收时弹出软键盘，界面会卡顿,可能和6410的显示性能有关
            //直接刷新显示，接收数据量大时，卡顿明显，但接收与显示同步。
            //用线程定时刷新显示可以获得较流畅的显示效果，但是接收数据速度快于显示速度时，显示会滞后。
            //最终效果差不多-_-，线程定时刷新稍好一些。
            DispQueue.AddQueue(ComRecData);//线程定时刷新显示(推荐)

			/*
			runOnUiThread(new Runnable()//直接刷新显示
			{
				public void run()
				{
					DispRecData(ComRecData);
				}
			});*/
        }
    }


    private void DispRecData(ComBean ComRecData){
        StringBuilder sMsg=new StringBuilder();
//        sMsg.append(ComRecData.sRecTime);
//        sMsg.append("[");
//        sMsg.append(ComRecData.sComPort);
//        sMsg.append("]");
//
//            sMsg.append("[Txt] ");
//            sMsg.append(new String(ComRecData.bRec));
//
//            sMsg.append("[Hex] ");
            sMsg.append(MyFunc.ByteArrToHexx(ComRecData.bRec));

//        sMsg.append("\r\n");
        Log.e("data coming",sMsg.toString());

        readNewFeedback(sMsg.toString());



//        if ((iRecLines > 500) && (checkBoxAutoClear.isChecked()))//达到500项自动清除
//        {
//            editTextRecDisp.setText("");
//            editTextLines.setText("0");
//            iRecLines=0;
//        }

    }
    //----------------------------------------------------刷新显示线程

    private static class ServerThread  implements Runnable {
        boolean isLoop = true;
        String recTAG = "recevieM";
        private ExecutorService mExecutorService;
        //ServerSocket对象
        private ServerSocket mServerSocket;

        //  public static final String ADDRESS = "192.168.1.163";
        //  public static final int PORT = 4869;

        //    private static ServerSocket serverSocket = null;
        private Socket client = null;
        //private OutputStream dos = null;
        // private DataInputStream dis = null;
        ExecutorService clientExecutor = new ThreadPoolExecutor
                (10,10,0, TimeUnit.MILLISECONDS,new LinkedBlockingQueue(100));

        public ServerThread() {

            StartServer();
            //  handler.postDelayed(runnable, DELYED); //启动定时器
        }



        public void setIsLoop(boolean isLoop) {
            this.isLoop = isLoop;
        }

        public OutputStream getDos() {
            return null;
//            OutputStream os = soc.getOutputStream();
//            //String message = msg + "\r\n";
//            //os.write(message.getBytes());
//            String message = msg + "0D0A";
//            os.write(TransformUtils.hexStringToBytes(message));
//            os.flush();
        }

        public void   StartServer(){
            try
            {
                if(mServerSocket!=null){
                    mServerSocket.close();
                }
                //设置服务器端口
                mServerSocket = new ServerSocket(SERVERPORT);
                //创建一个线程池
                // mExecutorService = Executors.newCachedThreadPool();
                //用来临时保存客户端连接的Socket对象
                new Thread(ServerThread.this).start();
            }
            catch (IOException e)
            {
                Log.e("servertag", e.toString());
            }

        }
        public  void CloseServer(){
            try {
                mServerSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //        private int DELYED= 1000;
//        Handler handler = new Handler();
//        Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    handler.postDelayed(this, DELYED);
//                    Log.e("tag"+"->runnable定时器","senmsg");
//                    // SendToClient("this message from server:dongdongdong");
//                } catch (Exception e) {
//                    //   Log.e(tag+"->runnable定时器", e.toString());
//                    Log.e("tag"+"->runnable定时器", e.toString());
//                }
//            }
//        };
        public ServerThread(Socket clientSocket) {


            super();
            this.client = clientSocket;
            clientdos = new HashMap<String ,OutputStream>();
        }

        public static void  servex()
                throws Exception {
            ServerSocket  tcpServer = new ServerSocket(15001);
            // System.out.println("Listening");
            while (true) {
                //  Socket sock = ssock.accept();
                //  System.out.println("Connected");
                // new Thread(new MultiThreadServer(sock)).start();
                Socket clientw = tcpServer.accept();

            }
        }

        @Override
        public void run() {
            Socket client = null;
            try{
                while (true)
                {
                    //  Log.e(tag, "收到客户端连接。。。");
                    //接收客户连接并添加到list中
                    //  client = serverSocket.accept();
                    client = mServerSocket.accept();

                    //  mClientList.add(client);
                    //开启一个客户端线程
                    if(client!=null){

                        String string = client.getRemoteSocketAddress().toString();
                        Log.e(recTAG, string);
//                clientList.add(string);
//                clientMap.put(string, client);
                        // clientdis.put(string, client.getInputStream());
                        try {
                            if(clientdos!= null) {
                                clientdos.put(string, client.getOutputStream());
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        //  new Handlerx(client).run();
                        new Thread(new Handlerx(client)).start();
                        //   mExecutorService.execute(new ServerThread(client));
                        //  runxx();
                        //异常捕不到，客户端退出后，程序挂了
                        //    mExecutorService.execute(new ThreadServer(client));

                    }

                }
            }
            catch(Exception e){
                //  mClientList.remove(client);
                Log.e("23434tag", e.toString());
                mExecutorService.shutdown();
            }
        }
        public void runxx() {


            //  final Socket client = null;
            if(client != null) {
                String string = client.getRemoteSocketAddress().toString();
                Log.e(recTAG, string);
//                clientList.add(string);
//                clientMap.put(string, client);
                // clientdis.put(string, client.getInputStream());
                try {
                    clientdos.put(string, client.getOutputStream());
                } catch (IOException e) {
                    e.printStackTrace();
                }


                clientExecutor.execute(new Handlerx(client));
            }

        }
    }
    public static boolean  checksendv(String comingdata, String lcomingdata)
    {
        boolean result1 = true;
        boolean result2 = true;
        boolean result3 = true;
        boolean result = false;

        try {
//            if(lcomingdata.equals(comingdata))
//            {
//                return false ;
//            }
            //      int alllength = comingdata.length() - 3;
            String firstFour = "";
            if ((comingdata.length()) > 4) {
                firstFour = comingdata.substring(0, 4);
                if (firstFour.equals(headerData)) {

                    //               allCmdx = allCmdx.concat(CRC16.expandStr(tmpTmp));
//                            StringBuffer allCmd = CRC16.crc16x(allCmdx);
//                            final String cmd = allCmd.substring(0, 22);
                    //5AA50883C5E0000000E439
                    // C5E00000

                }

                else
                {
                    result3 =  false;
                }

            }
            else
            {
                result3 =  false;
            }



            result = result1 && result2 && result3;
        }
        catch(Exception ex)
        {
            //result = false;
            // renew();
        }

        return result;
    }
    public static String bytesToHexStringC(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        //LocalBroadcastManager
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    static class Handlerx implements Runnable{
        private Socket client;
        public Handlerx(Socket socket){
            this.client=socket;
        }
        private PrintWriter getWriter(Socket socket) throws IOException{
            OutputStream socketOut=socket.getOutputStream();
            return new PrintWriter(socketOut,true);
        }
        private BufferedReader getReader(Socket socket) throws IOException{
            InputStream socketIn=socket.getInputStream();
            return new BufferedReader(new InputStreamReader(socketIn));
        }
        public String echo(String msg){
            return "echo:"+msg;
        }
        public void run(){
            try {
                if (null != client) {
                    try {
                        InputStream is = client.getInputStream();

                        //  byte[] buffer = new byte[256 * 4];
                        byte[] buffer = new byte[256 * 4];
                        int length = 0;
                        while (!client.isClosed() && !client.isInputShutdown()
                                && ((length = is.read(buffer)) != -1)) {
                            if (length > 0) {
                                String message = new String(Arrays.copyOf(buffer,
                                        length)).trim();
                                String messagex = bytesToHexStringC(buffer);
                                Log.e("prereceiveTAG", messagex);
                                message = messagex.substring(0,22);
                                //如何避免多次发送
                                if (message.length() == 22)
                                { Log.e("receiveTAG", message);
                                    //  if (downtimes < 1) {
                                    //     downtimes = downtimes++;
                                    if(checksendv(message,"")) {
                                        Log.e("sendreceiveTAG", message);

                                        message = message.toUpperCase();
                                        sendStarttry(message );
                                    //    boolean isSendx = uartJnit.getInstance().sendCmds(message); //delete send 20200914
                                        Message sendmm = Message.obtain();
                                        sendmm.what = 1;
                                    //    xxHandler.sendEmptyMessage(sendmm.what);


                                       // read after send

                                        //  xlongClicked = true;
                                   //     ComA.sendHex(message);
//                                        if(isSendx) {
//                                            Log.e("send TAG", "send down: " + message);
//                                        }
                                    }
                                    //testbtnFeed(currentPosition, false);

                                }
                                //  writeAct(messagex.substring(0,50));
                                //5aa50d8200d1000100010000000019cb open
                                //5aa50d8200d1000000000000000034cb close



                                //Log.e(BackService,messagex)
                                // 收到服务器过来的消息，就通过Broadcast发送出去
//							if (messagex.equals("ok")) {// 处理心跳回复
//							//	Intent intent = new Intent(HEART_BEAT_ACTION);
//								//mLocalBroadcastManager.sendBroadcast(intent);
//							} else {
                                // 其他消息回复
                                //	STATE_SUCCESS_ACTION
                                //  TransformUtils.comingdata = messagex;
                                //userInfo.edit().putString("user_info",messagex);
                                //userInfo.edit().commit();
//                            Intent intent = new Intent(STATE_SUCCESS_ACTION);
//                            intent.putExtra("message", messagex);
//                            mLocalBroadcastManager.sendBroadcast(intent);
                            }
                        }
                        synchronized (this) {
                            String string = client.getRemoteSocketAddress().toString();
                            clientdos.remove(string);
                        }

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            } finally {
                //  System.out.println("关闭连接：" + socket.getRemoteSocketAddress().toString());
                synchronized (this) {
                    //   --sum;
                    String string = client.getRemoteSocketAddress().toString();
                    //  clientMap.remove(string);
                    // clientList.remove(string);
                    clientdos.remove(string);
                    try {
                        if(client!=null)
                            client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
//                   finally{
//                        try {
//                            if(socket!=null)
//                                socket.close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
        }
    }

    private class DispQueueThread extends Thread{
        private Queue<ComBean> QueueList = new LinkedList<ComBean>();
        @Override
        public void run() {
            super.run();
            while(!isInterrupted()) {
                final ComBean ComData;
                while((ComData=QueueList.poll())!=null)
                {
                    runOnUiThread(new Runnable()
                    {
                        public void run()
                        {
                             DispRecData(ComData);
                        }
                    });
                    try
                    {
                        Thread.sleep(10);//显示性能高的话，可以把此数值调小。
                    } catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }

        public synchronized void AddQueue(ComBean ComData){
            QueueList.add(ComData);
        }
    }
    public class CountTimer extends CountDownTimer {
        private Context context;

        /**
         * 参数 millisInFuture       倒计时总时间（如60S，120s等）
         * 参数 countDownInterval    渐变时间（每次倒计1s）
         */
        public CountTimer(long millisInFuture, long countDownInterval,Context context) {
            super(millisInFuture, countDownInterval);
            this.context=context;
        }
        // 计时完毕时触发
        @Override
        public void onFinish() {
            //     UIHelper.showMainActivity((Activity) context);
            haveFinished = true;
            //jmp
            //  Intent intent = new Intent(Main2Activity.this, startActivity.class);
            //  startActivity(intent);
          touchjmp("");


        }
        // 计时过程显示
        @Override
        public void onTick(long millisUntilFinished) {
            Log.e("timing: ",String.valueOf(millisUntilFinished));
        }
    }

    private void touchjmpback(String cmdOne) {
        new Thread() {
            public void run() {
                super.run();
                try {
                    Message msg = Message.obtain();
                    msg.what = 3;
                    String cmdOnex = "0";
                    msg.obj = cmdOnex;
                    Bundle bundle = new Bundle();
                    bundle.putString("jmppageno",cmdOnex);

                    msg.setData(bundle);

                    mHandler.sendMessage(msg);
                    //  startActivity
                    //bring2Front();
                    //  stopLocation();

                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    Thread.sleep((long) TIMER_INTERVAL);
                } catch (InterruptedException e2) {
                    e2.printStackTrace();

                }
            }


        }.start();
    }
    private void touchjmp(String cmdOne) {
        new Thread() {
            public void run() {
                super.run();
                try {
                    Message msg = Message.obtain();
                    msg.what = 3;
                    String cmdOne = "29";
                    msg.obj = cmdOne;
                    Bundle bundle = new Bundle();
                    bundle.putString("jmppageno",cmdOne);

                    msg.setData(bundle);

                    mHandler.sendMessage(msg);
                  //  startActivity
                    bring2Front();
                  //  stopLocation();

                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    Thread.sleep((long) TIMER_INTERVAL);
                } catch (InterruptedException e2) {
                    e2.printStackTrace();

                }
            }


        }.start();
    }

    private void bring2Front()
    {
        ActivityManager activtyManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTaskInfos = activtyManager.getRunningTasks(3);
        for (ActivityManager.RunningTaskInfo runningTaskInfo : runningTaskInfos)
        {
            if (this.getPackageName().equals(runningTaskInfo.topActivity.getPackageName()))
            {
                activtyManager.moveTaskToFront(runningTaskInfo.id, ActivityManager.MOVE_TASK_WITH_HOME);
                return;
            }
        }
    }
    private class DispTimeThread extends Thread{
        // private Queue<ComBean> QueueList = new LinkedList<ComBean>();
        @Override
        public void run() {
            super.run();
            while(!isInterrupted()) {
                //   final ComBean ComData;
                while(true)
                {
                    runOnUiThread(new Runnable()
                    {
                        public void run()
                        {
                            //  DispRecData(ComData);
                            oldtimecyc();
                        }
                    });
                    try
                    {
                        sleep(5000);//显示性能高的话，可以把此数值调小。
                    } catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                    break;
                }
            }
        }

        //  public synchronized void AddQueue(ComBean ComData){
        //    QueueList.add(ComData);
    }
}
